RBG-LED全色域灯的驱动模块编写
立即下载
资源介绍:
RBG_LED全色域灯的驱动模块编写
# coding: utf-8
import RPi.GPIO as GPIO
import time
# 定义RGB LED连接的GPIO引脚
RGB_RED = 18
RGB_GREEN = 19
RGB_BLUE = 20
#初始化LED
def Init_RBG_LED():
# 设置GPIO模式为BCM(Broadcom SOC channel)
GPIO.setmode(GPIO.BCM)
# 设置引脚为输出模式
GPIO.setup(RGB_RED, GPIO.OUT)
GPIO.setup(RGB_GREEN, GPIO.OUT)
GPIO.setup(RGB_BLUE, GPIO.OUT)
# 创建一个函数来设置LED颜色(red, green, blue只能GPIO.HIGH,或GPIO.LOW)
def set_led_color(red, green, blue):
GPIO.output(RGB_RED, red)
GPIO.output(RGB_GREEN, green)
GPIO.output(RGB_BLUE, blue)
#设置LED为红色
def set_red():
set_led_color(GPIO.HIGH, GPIO.LOW, GPIO.LOW)
# 设置LED为绿色
def set_green():
set_led_color(GPIO.LOW, GPIO.HIGH, GPIO.LOW)
# 设置LED为蓝色
def set_blue():
set_led_color(GPIO.LOW, GPIO.LOW, GPIO.HIGH)
# 设置LED为白色(所有颜色都亮)
def set_white():
set_led_color(GPIO.HIGH, GPIO.HIGH, GPIO.HIGH)
# 设置LED为关闭(所有颜色都熄灭)
def set_off():
set_led_color(GPIO.LOW, GPIO.LOW, GPIO.LOW)
# 设置LED为紫色
def set_purple():
set_led_color(GPIO.HIGH, GPIO.LOW, GPIO.HIGH)
# 设置LED为黄色
def set_yellow():
set_led_color(GPIO.HIGH, GPIO.HIGH, GPIO.LOW)
# 设置LED为青色
def set_cyan():
set_led_color(GPIO.LOW, GPIO.HIGH, GPIO.HIGH)
# 示例:闪烁LED(红绿蓝依次闪烁)
def blink_led():
try:
while True:
set_white()
time.sleep(0.55)
set_red()
time.sleep(0.55)
set_green()
time.sleep(0.55)
set_blue()
time.sleep(0.55)
set_purple()
time.sleep(0.55)
set_yellow()
time.sleep(0.55)
set_cyan()
time.sleep(0.55)
except KeyboardInterrupt: # 捕获键盘中断以安全退出
set_off() # 关闭led
GPIO.cleanup()
if __name__ == "__main__":
GPIO.setwarnings(False) # 禁用GPIO警告
Init_RBG_LED() #初始化LED
blink_led() #彩色闪烁呼吸测试