首页 编程设计Python编程正文

树莓派RGB LED实验(python程序)

仁镜 Python编程 2018-12-15 17:20:53 2117 1 树莓派Python语言

一、接线图

   按照下图将RGB LED接到树莓派上。

02_RGB_LED_bb.jpg

二、Python程序

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

colors = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF]
R = 11
G = 12
B = 13

def setup(Rpin, Gpin, Bpin):
global pins
global p_R, p_G, p_B
pins = {'pin_R': Rpin, 'pin_G': Gpin, 'pin_B': Bpin}
GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
for i in pins:
GPIO.setup(pins[i], GPIO.OUT)   # Set pins' mode is output
GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led
p_R = GPIO.PWM(pins['pin_R'], 2000)  # set Frequece to 2KHz
p_G = GPIO.PWM(pins['pin_G'], 1999)
p_B = GPIO.PWM(pins['pin_B'], 5000)
p_R.start(100)      # Initial duty Cycle = 0(leds off)
p_G.start(100)
p_B.start(100)

def map(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

def off():
for i in pins:
GPIO.output(pins[i], GPIO.HIGH)    # Turn off all leds

def setColor(col):   # For example : col = 0x112233
R_val = (col & 0xff0000) >> 16
G_val = (col & 0x00ff00) >> 8
B_val = (col & 0x0000ff) >> 0

R_val = map(R_val, 0, 255, 0, 100)
G_val = map(G_val, 0, 255, 0, 100)
B_val = map(B_val, 0, 255, 0, 100)
p_R.ChangeDutyCycle(100-R_val)     # Change duty cycle
p_G.ChangeDutyCycle(100-G_val)
p_B.ChangeDutyCycle(100-B_val)

def loop():
while True:
for col in colors:
setColor(col)
time.sleep(1)

def destroy():
p_R.stop()
p_G.stop()
p_B.stop()
off()
GPIO.cleanup()

if __name__ == "__main__":
try:
setup(R, G, B)
loop()
except KeyboardInterrupt:
destroy()


版权声明

1.本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行测试。
2.本站资源仅供学习和交流使用,版权归资源原作者所有,请在下载后24小时之内自觉删除。
3.若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,与本站无关。
4.若内容涉及侵权或违法信息,请联系本站管理员进行下架处理,邮箱ganice520@163.com(本站不支持其他投诉反馈渠道,谢谢合作)

本文链接:http://www.apod.cc/index.php/post/13.html

发表评论

评论列表(1人评论 , 2117人围观)