3.1 PWM - LED Fade
We have used LED to make a running light before. In this example, we will learn how to make a fading light with PWM. The brightness of the LED light will change as the PWM duty cycle.
Introduction
PWM stands for Pulse-Width Modulation, a technique that uses a varying duty cycle to represent a signal as a rectangular wave. It's used to control the average amplitude or power of an electrical signal.
The two primary components of a Pulse Width Modulation (PWM) signal are frequency and duty cycle:
FrequencyThe rate at which a PWM signal switches between high and low voltages, measured in Hertz (Hz).
Duty cycleThe percentage of time a PWM signal is at a high voltage, expressed as a ratio or percentage.

PWM can be used to control the brightness of an LED by adjusting the duty cycle. If We generate a PWM signal to the anode(+) pin, the LED's brightness is in proportion to PWM duty cycle. PWM duty cycle varies from 0 to 255. The bigger the PWM duty cycle is, the brighter the LED is.

Hardware Circuit
1. Parts Required
Here’s a list of the parts to you need to build the circuit:
ESP32-S3-N16R8
LED
330 - 1k Ohm resistor
Breadboard
Jumper wires
2. Wiring
Before proceeding, you need to wire a circuit with an LED. The positive pole of the LED is connected to the pin 14 of the development board, and a resistor is connected in series. The negative pole is connected to GND, as shown below:

Usually, it requires a resistor to protect LED from burning. The resistance's value depends on the LED's specification.
Coding and Testing
1. Arduino functions for PWM
The analogWrite() function 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 rectangular wave of the specified duty cycle until the next call on the same pin.
pin: the Arduino pin to write to. Allowed data types: int
value: the duty cycle between 0 (off) and 255 (on). Allowed data types: int
Copy the following code to your IDE.
2. Uploading the Code
Refer the previous tutorial: 2.1 GPIO - LED Blink
Summary
In this section, we use analogWrite() function writes an analog value (PWM wave) to a pin to change the LED brightness.
Finally, if you want to learn more about other controllers, take a look at our Youtube channel:
Last updated