Raspberry Breathing Light
In this project, we will realize the effect of breathing light. That is, the brightness of LED will be changed from dark to light, and then from light to dark.
In this project, the electronic hardware we need to use is as follows:
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - LED Pack
Connect the LED to D18.
Write a Program
To realize the effect of breathing light, we need to use arithmetic operators to operate the duty cycle of the PWM signal.First, declare the functions in the library we need to use, and set the pins.
After setting the pin, use the “freq()" function to set the frequency of the PWM signal to 500:
Through analysis, we can find that the breathing light is actually composed of two parts. The first part is that the LED lights up gradually from the dim state, and enters the second part when the brightness reaches the maximum. In the second part, the brightness of the LED will begins to decay until it goes out. Repeating these two parts in alternation, we can realize the effect of a breathing light.
We can use two while-loop statements to realize the effects of these two parts. First, we set a variable "val" to help us adjust the duty cycle of the PWM signal. At the beginning of the program, we set val to 0:
Then we’ll work on the first part, where the LED lights up gradually:
In this program, we increase the value of “val" by 50 every millisecond until it is greater than 65535, and use the “duty_u16" function to adjust the duty cycle of the PWM signal using this same value.
When the value of “val" is greater than 65535, our code will exit the first while-loop and enter the next while-loop. Similarly, to make the light dim gradually, we keep decreasing the value of “val" until it is 0.
Then, we will place both loops in another “while True" loop to make the two parts of the program run continuously, and the effect of breathing light is completed.
Use a USB cable to connect Pico to the computer, click the “run" button to save the program to any location, you can see the program in action.