16. LED Brightness Control Using PWM

Analyzing the task above, we need to vary the LED's brightness over specific time intervals.

As we know, PWM (Pulse Width Modulation) is used to control LED brightness.

Also, we have to vary the LED brightness from 0% to 100% in 2 seconds, then from 100% back to 0% in 1 second.

To vary LED brightness smoothly using PWM with N discrete steps (e.g., 256 steps for 8-bit PWM), calculate the delay per brightness step as:

  • Rise delay per step = (Total rise time) ÷ (Number of PWM steps)
  • Fall delay per step = (Total fall time) ÷ (Number of PWM steps)

Examples:

  • With 256 PWM steps:
    • Rise delay per step = 2 seconds ÷ 256 ≈ 7.8125 milliseconds
    • Fall delay per step = 1 second ÷ 256 ≈ 3.906 milliseconds
  • With 10,000 PWM steps:
    • Rise delay per step = 2 seconds ÷ 10,000 ≈ 200 microseconds
    • Fall delay per step = 1 second ÷ 10,000 ≈ 100 microseconds
  • With 4096 PWM steps:
    • Rise delay per step = 2 seconds ÷ 4096 ≈ 488.281 microseconds
    • Fall delay per step = 1 second ÷ 4096 ≈ 244.140 microseconds

Avoid flickering of LED: Human eyes can detect flicker below ~100 Hz. Always use a PWM frequency above 200 Hz (commonly 500 Hz–1 kHz for LEDs).

Hardware Connection

  • We can connect the LED to any PWM pin.
  • A 3 mm red LED has a forward voltage of about 1.8 V, and to safely allow around 10 mA current, the LED must be connected with a proper series resistor.

Calculating the Resistor Value

Case 1: 5V Supply

  • LED forward voltage (Vf) = 1.8V (from datasheet)
  • Voltage across resistor (VR) = Supply voltage – Vf = 5V – 1.8V = 3.2V
  • Resistor value (R) = VR / I = 3.2V / 10 mA = 320 Ω

Standard resistor values near 320 Ω: 330 Ω or 300 Ω (whichever is available).

Similarly, Case 2: 3.3V Supply

  • Voltage across resistor (VR) = 3.3V – 1.8V = 1.5V
  • Resistor value (R) = 1.5V / 10 mA = 150 Ω

Standard resistor value: 150 Ω.

So, by selecting a proper resistor, LED, and calculating the delay correctly, we can implement the task.

Below are the solutions to the given task using different microcontrollers

  1. STM32
  2. ESP32
  3. Arduino UNO

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!