4834浏览
查看: 4834|回复: 1

【 树莓派教程】——用树莓派实现RGB LED的颜色控制

[复制链接]
RGB LED颜色控制
  1. #!/usr/bin/env python
  2. import RPi.GPIO as GPIO
  3. import time
  4. colors = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0xFFFFFF, 0x9400D3]
  5. pins = {'pin_R':11, 'pin_G':12, 'pin_B':13}  # pins is a dict
  6. GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
  7. for i in pins:
  8.         GPIO.setup(pins[i], GPIO.OUT)   # Set pins' mode is output
  9.         GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led
  10. p_R = GPIO.PWM(pins['pin_R'], 2000)  # set Frequece to 2KHz
  11. p_G = GPIO.PWM(pins['pin_G'], 2000)
  12. p_B = GPIO.PWM(pins['pin_B'], 5000)
  13. p_R.start(100)      # Initial duty Cycle = 100(leds off)
  14. p_G.start(100)
  15. p_B.start(100)
  16. def map(x, in_min, in_max, out_min, out_max):   # 将一个数从一个区间线性映射到另一个区间,比如将0~100之间的一个数映射到0~255之间
  17.         return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
  18. def setColor(col):   # For example : col = 0x112233
  19.         R_val = (col & 0xFF0000) >> 16
  20.         G_val = (col & 0x00FF00) >> 8
  21.         B_val = (col & 0x0000FF) >> 0
  22.         
  23.         R_val = map(R_val, 0, 255, 0, 100)   # change a num(0~255) to 0~100.
  24.         G_val = map(G_val, 0, 255, 0, 100)
  25.         B_val = map(B_val, 0, 255, 0, 100)
  26.         
  27.         p_R.ChangeDutyCycle(100 - R_val)     # Change duty cycle
  28.         p_G.ChangeDutyCycle(100 - G_val)
  29.         p_B.ChangeDutyCycle(100 - B_val)
  30. try:
  31.         while True:
  32.                 for col in colors:
  33.                         setColor(col)
  34.                         time.sleep(0.5)
  35. except KeyboardInterrupt:
  36.         p_R.stop()
  37.         p_G.stop()
  38.         p_B.stop()
  39.         for i in pins:
  40.                 GPIO.output(pins[i], GPIO.HIGH)    # Turn off all leds
  41.         GPIO.cleanup()
复制代码

凌风清羽  中级技匠
 楼主|

发表于 2016-3-27 20:10:06

待我的树莓派3到了测试一下
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail