NodeMCU PWM with Arduino IDE
Introduction
Pulse Width Modulation (PWM) is a technique by which width of a pulse is varied while keeping the frequency of the wave constant.
PWM Generation
A period of a pulse consists of an ON cycle (VCC) and an OFF cycle (GND). The fraction for which the signal is ON over a period is known as a duty cycle.
E.g. A pulse with a period of 10ms will remain ON (high) for 2ms.Therefore, duty cycle will be
D = 2ms / 10ms = 20%
Through PWM technique, we can control the power delivered to the load by using ON-OFF signal. The PWM signals can be used to control the speed of DC motors and to change the intensity of the LED. Moreover, it can also be used to generate sine signals. Pulse Width Modulated signals with different duty cycle are shown below.
NodeMCU based ESP8266 has the functionality of PWM interfaces via software programming. It is achieved with the timer interruption method. PWM frequency range for ESP8266 is adjustable up to 1KHz.
PWM pins on NodeMCU Kit
Arduino function for NodeMCU PWM
analogWrite(pin, dutycycle)
: Enables software PWM on the specified pin. duty cycleis in the range from 0 to PWMRANGE, i.e. 1023 by default.
analogWrite(pin, 0)
: Disables PWM on specified pin.
analogWriteRange(new_range)
: This function is used to change PWM range (duty cycle).
analogWriteFreq(new_frequency)
: PWM frequency is 1kHz by default. Call this function to change it with new frequency.PWM frequency is in the range 1 – 1000Khz.
Example
Let’s write an Arduino sketch to set PWM on 6thpin of NodeMCU and vary it’s duty cycle with the potentiometer connected to the ADC pin of NodeMCU. Here we connect LED on PWM pin to visualize effect (Brightness of LED) of PWM variation.
Arduino Sketch for PWM