Arduino Code for ESP32 to Fade in and out the On-Board LED with PWM

Pete 0

Pulse-width modulation on an ESP32 module is achieved using the LED control (LEDC) peripheral and is primarily designed to control the intensity of LED’s. The ESP32 has 16 channels (0-15) for 8, 10, 12, 15 bit resolution for PWM generation. The maximum PWM frequency with a duty resolution of 10 bits is 78.125KHz. For duty resolution of 8 bits, the maximal frequency is 312.5 kHz. The available duty levels are (2^bit_num)-1, where the duty bit resolution can be 1-15. The maximal frequency is 80000000 / 2^bit_num.

Testing is simple due to the on-board LED is on GPIO 2 and fully controllable. No need to do any soldering and just an ESP32 module USB cable and a PC is all that is needed. Ultimately I want to control a RGB 5050 LED strip with music sent from my phone via Bluetooth so stay tuned.

What you will need:

  • ESP32 Module
  • PC
  • USB Cable

I will mention that when using the Arduino IDE to send your code to the ESP32 module I’ve always had to hold the boot button down when the IDE is connecting to the module during the upload and then letting the button go once you see it start uploading.

Below is the Arduino Sketch. You are free to use and modify as you please. You can download it here: ESP32_PWM_LED

// =====================================
// Arduino ESP32 code to fade in and out the On-Board LED
// By:
// 12-27-2020
// -------------------------------------
const int ledPin = 2;//On-Board LED  
int dc = 0;//read-write

// setting PWM properties
const int freq = 4000;//Freq in Hz
const int ledChannel = 0;//There are 16 channels 0-15
const int resolution = 8;//8,10,12,15 Bit Resolution  8-bit=255 10-bit=1024

void setup(){
  // send the PWM configuration
  ledcSetup(ledChannel, freq, resolution);

  // attach the channel to the GPIO to be controlled
  ledcAttachPin(ledPin, ledChannel);

void loop(){
  // increase the LED brightness
  for(int i = 0; i <= 255; i++){
  // decrease the LED brightness
  for(int i = 255; i >= 0; i--){

void LED(){
  ledcWrite(ledChannel, dc);


Chief Editor for --------- Author, Publisher, Blogger, Amateur Astronomer, Content Creator, Hobbyist, Welder/Fabricator, Dirt Track Racer, Patriot.

Leave a Reply