Last active
January 11, 2024 19:01
-
-
Save turnipsoup/9bd54b1d049adb92eb85f7c3edaf948b to your computer and use it in GitHub Desktop.
Control RGB LED with MicroPython using PWM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from machine import Pin, PWM | |
from time import sleep | |
import random | |
pwm = PWM(Pin(15)) | |
pwm2 = PWM(Pin(13)) | |
pwm3 = PWM(Pin(11)) | |
pwm.freq(1000) | |
pwm2.freq(1000) | |
pwm3.freq(1000) | |
pwm_dict = { | |
'red': pwm, | |
'green': pwm2, | |
'blue': pwm3 | |
} | |
def led_off(): | |
""" | |
Turn off all colors on LED | |
""" | |
for p in pwm_dict.values(): | |
p.duty_u16(0) | |
def led_on(colors): | |
""" | |
Turn on the color of each color passed in a list. Supports ['red', 'green', 'blue'] or shorter. | |
Is an even mix | |
""" | |
led_off() | |
for p in colors: | |
pwm_dict[p].duty_u16(int(65024/len(colors))) | |
def led_on_rgb_code(rgb_values): | |
""" | |
Takes an input list of RGB values between 0,255 and approximates them on the RGB LED | |
Example: [255, 400, 137] | |
""" | |
red = 254 * rgb_values[0] | |
green = 254 * rgb_values[1] | |
blue = 254 * rgb_values[2] | |
pwm_dict['red'].duty_u16(int(red)) | |
pwm_dict['green'].duty_u16(int(green)) | |
pwm_dict['blue'].duty_u16(int(blue)) | |
if __name__ == "__main__": | |
led_on_rgb_code([255, 102, 102]) | |
sleep(1) | |
led_off() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment