SunFounder ESP32 Starter Kit
(continued from previous page)
# Set the PWM frequency
red.freq(1000)
green.freq(1000)
blue.freq(1000)
def set_color(r, g, b):
red.duty(r)
green.duty(g)
blue.duty(b)
while True:
# Set different colors and wait for a while
set_color(1023, 0, 0) # Red
time.sleep(1)
set_color(0, 1023, 0) # Green
time.sleep(1)
set_color(0, 0, 1023) # Blue
time.sleep(1)
set_color(1023, 0, 1023) # purple
time.sleep(1)
When the script runs, you will see the RGB LEDs display red, green, blue and purple, and so on.
Learn More
You can also set the color you want with the following code with the familiar color values of 0~255.
Note:
• Open the 2.3_colorful_light_rgb.py file located in the esp32-starter-kit-main\micropython\
codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute
it.
• Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.
from machine import Pin, PWM
import time
# Define the GPIO pins for the RGB LED
RED_PIN = 27
GREEN_PIN = 26
BLUE_PIN = 25
# Set up the PWM channels
red = PWM(Pin(RED_PIN))
green = PWM(Pin(GREEN_PIN))
blue = PWM(Pin(BLUE_PIN))
# Set the PWM frequency
red.freq(1000)
green.freq(1000)
blue.freq(1000)
(continues on next page)
318 Chapter 3. For MicroPython User