LED GURUcosycom.com
PAGE 087 OF 150 · TIMERS, FLASHERS & DIMMING

Fading LEDs with a Microcontroller

Slowly changing duty cycle creates a smooth fade.

LED SYMBOLTriangle points from anode to cathode; the arrows show light leaving the part.

Simple fade

Use a PWM-capable pin and change its duty value in small steps, with a short pause between each, to fade up and down.

  • Loop from 0 up to 255, setting the value each time.
  • Then loop from 255 back to 0.
  • A delay of 5 to 10 milliseconds per step gives a pleasant speed.

Improvements

Use a gamma lookup table for an even-looking fade, and prefer timing with the millis counter instead of delay so the board can do other jobs while fading. A breathing effect follows a sine curve instead of a straight ramp.

REMEMBER
Switching an LED on and off quickly can look like steady dimmer light.

Try it yourself

Sketch the circuit on paper first, calculate the values, then build it on a solderless breadboard using a low-voltage supply. Measure with a multimeter before you make anything permanent.

Explore LED clocks, stopwatches and electronics at cosycom.com.

Watch: COSYCOM channel videos

www.youtube.com/@cosycom