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

2016-03-278946
AI 快速预览详细 收起
本文介绍了如何使用树莓派实现RGB LED的颜色控制。首先,通过设置GPIO引脚和PWM频率,初始化树莓派。然后,定义了map函数,将0~255之间的数值线性映射到0~100之间,实现颜色值的精确控制。最后,通过循环遍历预设的颜色列表,调用setColor函数实现颜色的切换。这个项目适合编程新手,可以帮助他们理解GPIO和PWM的基本概念,并且能够快速上手实践。
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()
复制代码

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(1)
凌风清羽
凌风清羽
作者
待我的树莓派3到了测试一下
- 没有更多了 -