ESP8266 PWM Example

In This post ESP8266 PWM example explains how to use the Pulse Width Modulation (PWM)  with the ESP8266. We will use

analogWrite(PIN,VALUE);

ESP8266 can generate PWM on all IO pins. The ESP8266 analogWrite is different than the Arduino Uno. ESP8266 uses 10-bit resolution for PWM generation PWM value varries from 0 to 1023. Arduino Uses 8-Bit Resolution i.e.PWM range is 0-254.

analogWrite, Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 1 KHz.

LED Fading Program using ESP8266 PWM

/* Generates PWM on Internal LED Pin GPIO 2 of ESP8266*/

#include <ESP8266WiFi.h>
#define LED 2

int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// Power on setup
void setup() {
Serial.begin(115200);
pinMode(LED,OUTPUT);
}

// Main Program Loop
void loop() {
//PWM Value varries from 0 to 1023 
Serial.println("10 % PWM");
analogWrite(LED,102);
delay(2000);

Serial.println("20 % PWM");
analogWrite(LED,205);
delay(2000);

Serial.println("40 % PWM");
analogWrite(LED,410);
delay(2000);

Serial.println("70 % PWM");
analogWrite(LED,714);
delay(2000);

Serial.println("100 % PWM");
analogWrite(LED,1024);
delay(2000);

//Continuous Fading
Serial.println("Fadding Started");
while(1)
{
// set the brightness of pin 9:
analogWrite(LED, brightness);

// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 1023) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(10);
}
}

Upload program in your ESP and open serial monitor.


In this tutorial we’ve shown you ESP8266 PWM Example. I hope you like this ESP8266 PWM Example. Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

We have other tutorials with ESP32 that you may find useful:

You may like also:


Like FB Page

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. I am a tech blogger and an IoT Enthusiast. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning! Follow and send tweets me on @harshvardhanrvm

One thought on “ESP8266 PWM Example

Leave a Reply

%d bloggers like this: