3.18 Breathing LED

3.18.1 Overview

PWM breathing LED utilizes on-board programmable PWM to output analog waveform. After powering on, LED brightness can be adjusted through duty cycle of the waveform to eventually realize a breathing light.

In this way, ambient light can be simulated by changing LED brightness along with time. Also, breathing LED can form a colorful mini light show to construct a tranquil and warm environment.

3.18.2 Working Principle

PWM controls analog output via digital means, which are able to adjust the duty cycle of the wave (a signal circularly shifting between high level and low level).

digital ports of voltage output are LOW and HIGH, which respectively correspond to 0V and 5V. Generally, we define LOW as 0 and HIGH as 1. will output 500 signals of 0 or 1 within 1s. If they are 500 “1”s, 5V will be output. Oppositely, if they are all 0s, the output will be 0V. Or if they are 010101010101…, the average output will be 2.5V. In other words, output ratio of 0 and 1 affects the voltage value.

Honestly, it differs from real continuous output, yet the more 0 and 1 signals are output per unit time, the more accurate the control will be.

6-18

3.18.3 Test Code

In Files, open 3-18-gradientLight.py and click .

Code:

'''
 * Filename    : 3-18-gradientLight
 * Thonny      : Thonny 4.1.4
 * Auther      : http//www.keyestudio.com
'''
from machine import Pin, PWM  
import time  
  
# set PWM pin and frequency  
pwm_pin = Pin(23, Pin.OUT)  
pwm = PWM(pwm_pin, freq=1000)  # set frequency to 1000Hz  
  
# breathing LED  
while True:  
    for duty in range(0, 1024, 5):  # gradually light up
        pwm.duty(duty)  
        time.sleep_ms(10)  # add a delay for better observing  
    for duty in range(1023, -1, -5):  # gradually dim out
        pwm.duty(duty)  
        time.sleep_ms(10)

Result:

After uploading code, the red LED gradually lights on and dims out, in a circulation. It “breathes” evenly.