Skip to main content

Lesson 4: PWM - Make LEDs "Breathe"

๐Ÿ“Œ Learning Objectivesโ€‹

  1. Understand what PWM is
  2. Understand the concept of duty cycle
  3. Learn to control LED brightness with PWM
  4. Create an LED breathing effect

๐ŸŽฏ What is PWM?โ€‹

PWM = Pulse Width Modulation

A Useful Analogyโ€‹

Imagine you're turning a light on and off very quickly:

  • On time longer, off time shorter โ†’ light appears bright
  • On time shorter, off time longer โ†’ light appears dim
  • On and off times equal โ†’ medium brightness

This is the basic principle of PWM!


๐Ÿ“Š Key Concept: Duty Cycleโ€‹

Duty Cycle = High time รท Period time

Duty CycleLED Brightness
0%Completely off
25%Dim
50%Medium
75%Bright
100%Full brightness

๐ŸŽ›๏ธ Common Uses of PWMโ€‹

  1. Control LED brightness (breathing lights)
  2. Control motor speed
  3. Generate sound (buzzers)
  4. Servo angle control

๐Ÿ”ง Using PWM in JoyKitโ€‹

JoyKit has built-in WS2812B LEDs that can be controlled for color and brightness.

InstructionFunction
0xE6Set LED mode
0xE7Configure breathing parameters
0xE4Set LED color

๐Ÿ”ฌ Classroom Demo Project: LED Breathing Lightโ€‹

Project Goalโ€‹

Make an LED fade from dim to bright, then bright to dim, repeatedly, creating a "breathing" effect.

Hardware Requirementsโ€‹

  • Onboard WS2812B LED

Reference Programโ€‹

; LED breathing light project
000 C7 0001 0000 ; Enable WS2812B
001 E6 0002 0000 ; Set to breathing mode
002 E7 000A 0000 ; Configure breathing parameters (steps=10, interval=0, start=0, end=0)
003 E4 00FF 0000 ; Red
004 02 0FA0 0000 ; delay
005 0E 0003 0000 ; loop

Teaching Suggestionsโ€‹

  1. Change colors: R31/R32/R33 represent Red/Green/Blue
  2. Change speed: Adjust delay parameters
  3. Add button control: Press once to start breathing, press again to stop

๐Ÿ“ˆ Observing PWM Waveformsโ€‹

If you have an oscilloscope, you can observe the PWM signal:

High  โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘
โ†‘ โ†‘
On Off
Time Time
  • High = LED on
  • Low = LED off
  • High ratio = brightness

๐Ÿ’ก Advanced: Simulating PWM with Codeโ€‹

While JoyKit has hardware PWM, we can simulate it with software:

; Software simulated PWM (simplified)
000 10 0000 0005 ; R0 = 5 (brightness)
001 01 0001 0000 ; LED on
002 02 0005 0000 ; delay R0
003 01 0000 0000 ; LED off
004 02 000A 0000 ; delay (15-R0)
005 0E 0001 0000 ; loop

๐ŸŽ‰ Summaryโ€‹

What we learned today:

  • โœ… PWM = Pulse Width Modulation
  • โœ… Duty cycle determines brightness
  • โœ… JoyKit LEDs have hardware breathing mode
  • โœ… Completed LED breathing light project
  • โœ… Can simulate PWM with software

Next lesson, we'll learn about I2C Protocol to see how microcontrollers communicate with sensors!