3.1 PWM - LED Fade
Last updated
Last updated
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.
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.
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
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:
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.
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:
Refer the previous tutorial: