Raspberry Control RGB LED to Display Different Colors in Turn
In the Introduction to Electronic Hardware, we mainly used the LED, which only has a single color. We can control the brightness of the light through the program, but we cannot change the color to present more diverse effects. In Project 1, we will control the RGB LED (ws2813 mini) to display different colors in turn.
Hardware Connection
In this project, the electronic hardware we need to use is as follows:
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - RGB LED (WS2813 Mini)
Connect the Pico and the Grove Shield, use a Grove data cable to connect the RGB LED to D18.
Write a Program
To interface with the new WS2813 RGB LED module, we will need a new library ws2812. py(2kB) to control the RGB LED. After downloading the library file and saving it in Pico, we can start to introduce the function library we need.
The functions used in the ws2812 library are as follows:
• pixels_fills() — RGB LED fill in color
• pixels_show() — RGB LED show color
First, introduce the function library that we need:
1 from ws2812 import WS2812
2 import utime
Next, define the display color of the RGB LED. We have listed the codes of common colors. If you want other colors, you can find them in the RGB Color Code List.
1 BLACK = (0, 0, 0)
2 RED = (255, 0, 0)
3 YELLOW = (255, 150, 0)
4 GREEN = (0, 255, 0)
5 CYAN = (0, 255, 255)
6 BLUE = (0, 0, 255)
7 PURPLE = (180, 0, 255)
8 WHITE = (255, 255, 255)
After defining the colors, create a Tuple named COLORS to collect all the colors that need to be displayed.
1 COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE)
Finally, define the RGB LED, traverse all the color elements in the COLORS Tuple through the “for" statement, and display them on the RGB LED. In order to display each color clearly, we will buffer them with a delay.
1 led = WS2812(18,1)#WS2812(pin_num, led_count)
2
3 while True:
4 print("fills")
5 for color in COLORS:
6 led.pixels_fill(color)#RGB LED fill in color
7
led.pixels_show() #RGB LED show color
8 utime.sleep(0.2)#delay
The complete program is as follows:
1 from ws 2812 import WS2812
2 import utime
3
4 BLACK = (0, 0, 0)
5 RED = (255, 0, 0)
6 YELLOW = (255, 150, 0)
7 GREEN = (0, 255, 0)
8 CYAN = (0, 255, 255)
9 BLUE = (0, 0, 255)
10 PURPLE = (180, 0, 255)
11 WHITE = (255, 255, 255)
12 COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE)
13
14 led = WS2812(18,1)#WS2812(pin_num, led_count)
15
16 while True:
17 print("fills") for color in COLORS:
18 led.pixels_fill(color)
19 led.pixels_show()
20 utime. sleep(0.2)
Use a USB cable to connect Pico to the computer, click the “run" button to save the program to any location. Now, you can see the RGB LED displays different colors.