Lesson 4: PWM - Make LEDs "Breathe"
๐ Learning Objectivesโ
- Understand what PWM is
- Understand the concept of duty cycle
- Learn to control LED brightness with PWM
- 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 Cycle | LED Brightness |
|---|---|
| 0% | Completely off |
| 25% | Dim |
| 50% | Medium |
| 75% | Bright |
| 100% | Full brightness |
๐๏ธ Common Uses of PWMโ
- Control LED brightness (breathing lights)
- Control motor speed
- Generate sound (buzzers)
- Servo angle control
๐ง Using PWM in JoyKitโ
JoyKit has built-in WS2812B LEDs that can be controlled for color and brightness.
Related Instructionsโ
| Instruction | Function |
|---|---|
0xE6 | Set LED mode |
0xE7 | Configure breathing parameters |
0xE4 | Set 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โ
- Change colors: R31/R32/R33 represent Red/Green/Blue
- Change speed: Adjust delay parameters
- 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!