xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python rpi_ws281x library All In One

Python rpi_ws281x library All In One

Raspberry Pi & Python & WS2812B RGB LED Strip

rpi_ws281x

from rpi_ws281x import PixelStrip, Color, ws

PixelStrip
Color

$ sudo pip install rpi_ws281x

$ sudo pip3 install rpi_ws281x

https://github.com/rpi-ws281x

https://github.com/rpi-ws281x/rpi-ws281x-python

API docs 💩

https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/library/rpi_ws281x.py#L72-L88

how to read these examples for guess the shit API 💩💩💩

https://github.com/rpi-ws281x/rpi-ws281x-python/tree/master/examples

https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/examples/neopixelclock.py#L48

ws

from rpi_ws281x import Color, PixelStrip, ws

# LED_STRIP = ws.SK6812_STRIP_RGBW
LED_STRIP = ws.SK6812W_STRIP

ws 等价于 rpi_ws281x

from rpi_ws281x import Color, PixelStrip, ws

# GRB ✅
STRIP_TYPE = ws.WS2811_STRIP_GRB
print("STRIP_TYPE =", STRIP_TYPE)
# STRIP_TYPE = 528384
from rpi_ws281x import PixelStrip, Color
# import rpi_ws281x

# GRB ✅
STRIP_TYPE = rpi_ws281x.WS2811_STRIP_GRB
print("STRIP_TYPE =", STRIP_TYPE)
# STRIP_TYPE = 528384

https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/examples/SK6812_white_test.py

bugs ❌

https://github.com/rpi-ws281x/rpi-ws281x-python/issues/95

#!/usr/bin/env python3
# coding: utf8

import time
import argparse
from rpi_ws281x import PixelStrip, Color, ws
# from rpi_ws281x import *

# LED strip configuration
LED_COUNT = 60            # Number of LED pixels.
LED_PIN = 18                  # BCM GPIO pin connected to the pixels (18 uses `PWM`).
# LED_PIN = 10               # GPIO pin connected to the pixels (10 uses `SPI` /dev/spidev0.0).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz) # ❓ 不同 LED 频率不同,5050 LED ❓
LED_DMA = 10                # DMA channel to use for generating signal (try 10)
LED_INVERT = False       # True to invert the signal (when using NPN transistor level shift)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
LED_CHANNEL = 0          # set to '1' for GPIOs 13, 19, 41, 45 or 53
#LED_STRIP = ws.WS2812B_STRIP
LED_STRIP = ws.SK6812_STRIP_GRB

# ...

rpi_ws281x API

class: RGBW
  func: __new__
  func: r
  func: g
  func: b
  func: w

func: Color

class: PixelStrip
  func: __init__
  func: __getitem__
  func: __setitem__
  func: __len__
  func: _cleanup
  func: setGamma
  func: begin
  func: show
  func: setPixelColor
  func: setPixelColorRGB
  func: getBrightness
  func: setBrightness
  func: getPixels
  func: numPixels
  func: getPixelColor
  func: getPixelColorRGB
  func: getPixelColorRGBW

class: Adafruit_NeoPixel

https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/library/rpi_ws281x/rpi_ws281x.py

errors ❌

💩 只会变白色,不会变成其他颜色

??? PWM 需要 hex 编码

#!/usr/bin/env python3
# coding: utf8

from time import sleep
from rpi_ws281x import PixelStrip, Color

# LED strip configuration:
LED_COUNT = 60        # Number of LED pixels.
LED_PIN = 18          # GPIO pin connected to the pixels (18 uses PWM!).
# LED_PIN = 10        # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10          # DMA channel to use for generating signal (try 10)
# color channel GRB ❓
LED_INVERT = True     # True to invert the signal (when using NPN transistor level shift)
LED_BRIGHTNESS = 50   # Set to 0 for darkest and 255 for brightest
LED_CHANNEL = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

# Create NeoPixel object with appropriate configuration.
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)

# Initialize the library (must be called once before other functions).
strip.begin()
print("Test beginning ✅")

def clear_buffer():
  for i in range(LED_COUNT):
    strip.setPixelColor(i, Color(0, 0, 0))
  strip.show()
  sleep(1)

def test():
  print("strip.numPixels() =", strip.numPixels())
  for i in range(strip.numPixels()):
    # white ✅
    # strip.setPixelColor(i, Color(255, 255, 255))
    # red ❌ 不生效 💩
    strip.setPixelColor(i, Color(255, 0, 0))
  strip.show()
  sleep(1)

try:
  test()
except KeyboardInterrupt:
  print('Ctrl + C exit ✅')
except RuntimeError as error:
  print("error =", error, error.args[0])
  pass
except Exception as error:
  print("exception =", error)
  raise error
finally:
  print("after three seconds, auto clear buffer! 👻")
  sleep(3.0)
  clear_buffer()
  print("Test finished 🎉")

exit()

image

https://github.com/rpi-ws281x/rpi-ws281x-python/issues/95#issuecomment-1549991731

LED_INVERT = False


#!/usr/bin/env python3
# coding: utf8

from time import sleep
from rpi_ws281x import PixelStrip, Color

# LED strip configuration:
LED_COUNT = 60        # Number of LED pixels.
LED_PIN = 18          # GPIO pin connected to the pixels (18 uses PWM!).
# LED_PIN = 10        # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10          # DMA channel to use for generating a signal (try 10)
# color channel GRB ❓
LED_INVERT = False     # True to invert the signal (when using NPN transistor level shift)
LED_BRIGHTNESS = 50   # Set to 0 for darkest and 255 for brightest
LED_CHANNEL = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

# Create a NeoPixel object with the appropriate configuration.
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)

# Initialize the library (must be called once before other functions).
strip.begin()
print("Test beginning ✅")

def clear_buffer():
  for i in range(LED_COUNT):
    strip.setPixelColor(i, Color(0, 0, 0))
  strip.show()
  sleep(1)

def test():
  print("strip.numPixels() =", strip.numPixels())
  for i in range(strip.numPixels()):
    # white ✅
    # strip.setPixelColor(i, Color(255, 255, 255))
    # red ❌
    strip.setPixelColor(i, Color(255, 0, 0))
  strip.show()
  sleep(1)

try:
  test()
except KeyboardInterrupt:
  print('Ctrl + C exit ✅')
except RuntimeError as error:
  print("error =", error, error.args[0])
  pass
except Exception as error:
  print("exception =", error)
  raise error
finally:
  print("after three seconds, auto clear buffer! 👻")
  sleep(3.0)
  clear_buffer()
  print("Test finished 🎉")

exit()

image

demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

RPi.GPIO

#!/usr/bin/env python3
# coding: utf8

import RPi.GPIO as GPIO

from datetime import datetime
import time
import sys

arg1 = sys.argv[1]
print("arg1 =", arg1);

# shell 获取时间戳 ✅
# SH_DATE=$(TZ=':Asia/Shanghai' date '+%Y-%m-%d %T');
# datetime = $(date '+%Y-%m-%d %T')

# Python 获取时间戳 ✅
now = datetime.now()
# 转换为指定的格式
currentTime = now.strftime("%Y-%m-%d %H:%M:%S")
print("⏰ current datetime =", currentTime);

# $ pinout 命令查看,或 https://pinout.xyz/
# 指定 BCM 模式下的 GPIO 针脚编号是 12
# 对应的物理针脚编号是 32
PIN = 12
# BCM 模式
GPIO.setmode(GPIO.BCM)

# 指定 GPIO 针脚为一个电流输出针脚
GPIO.setup(PIN, GPIO.OUT)
# 输出低电平
GPIO.output(PIN, GPIO.LOW)

# index
i = 0
# 类型转换,str => int
n = int(arg1)

print("n =", n)
print('开始闪烁⏳')

while (i < n):
  print("i =", i)
  # 高电平,LED 点亮
  GPIO.output(PIN, GPIO.HIGH)
  # 休眠 1 秒,防止 LED 长时间点亮烧坏了
  time.sleep(1.0)
  # 低电平,LED 熄灭
  GPIO.output(PIN, GPIO.LOW)
  # 休眠 1 秒
  time.sleep(1.0)
  i = i + 1

# 输出低电平,LED 关闭
# GPIO.output(PIN, GPIO.LOW)
# 清除,释放内存
GPIO.cleanup()

print('结束闪烁 👌🏻')

#!/usr/bin/env python3
# coding: utf8

from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
# GPIO.setwarnings(False)

PIN = 18
Hz = 4978
GPIO.setup(PIN, GPIO.OUT)
# 设置 GPIO 18 PIN 为 PWM 输出, PWM 脉冲频率为 4978Hz (2KHz ~ 5KHZ)
pwm = GPIO.PWM(PIN, Hz)
print('🔔 pwm =', pwm)
# 🔔 pwm = <RPi.GPIO.PWM object at 0x7f915fcd10>

print('\n开始鸣叫 🔔')
try:
  # DutyCycle 0.0 ~ 100.0
  pwm.start(0.0)
  pwm.ChangeDutyCycle(50.0)
  sleep(1)
  pwm.stop()
except KeyboardInterrupt:
  print('鸣叫 ❌')
finally:
  GPIO.cleanup()
  print('结束鸣叫 🔔')

"""

GPIO 18(PWM0)
GPIO 12(PWM0)

GPIO 13(PWM1)
GPIO 19(PWM1)

https://pinout.xyz/pinout/pwm

https://pinout.xyz/pinout/pin12_gpio18


`无源蜂鸣器`的特点:

1. 无源内部不带震荡源,所以如果用直流信号无法令其鸣叫。必须用`2K~5K`的方波去驱动它
2. 声音频率可控,可以做出“多来米发索拉西”的效果。(高阶玩家)
3. 在一些特例中,可以和 LED 复用一个控制口

💡: 使用无源蜂鸣器,只要输出不同频率的 PWM 方波(数字信号),即可发出不同的音符; 不同的音符组合起来就是一个曲子了, 可以用来播放音乐; ✅

模拟信号:连续性
数字信号: 非连续 0 ~ 1

https://www.cnblogs.com/xgqfrms/p/17404551.html


PWM (Pulse Width Modulation) 即 脉冲宽度调制,
是一种利用微处理器的数字输出来控制模拟电路的控制技术。

但是,需要注意的是 BCM2835 芯片只支持`两路` PWM 输出,
12 Pin 脚和 32 Pin 脚对应的都是 channel 1 的 PWM 输出,
即如果这两个 Pin 的功能都选择的是 PWM 输出,则它们输出的 PWM 是完全相同的;
同理 33 Pin脚和 35 Pin脚对应芯片 channel 2 的 PWM 输出;


"""


#!/usr/bin/env python3
# coding: utf8

import RPi.GPIO as GPIO
from time import sleep

# choose BCM numbering scheme.
GPIO.setmode(GPIO.BCM)
# red / green / blue
# GPIO.setup(17, GPIO.OUT)
# GPIO.setup(27, GPIO.OUT)
# GPIO.setup(22, GPIO.OUT)

# GPIO.setup list
LEDs = [17, 22, 27]
GPIO.setup(LEDs, GPIO.OUT)

# LED Duty Cycle / LED 占空比
# hz = input('Please define the frequency in Herz(recommended:75): ')
# reddc = input('Please define the red LED Duty Cycle: ')
# greendc = input('Please define the green LED Duty Cycle: ')
# bluedc = input('Please define the blue LED Duty Cycle: ')

# hz = 1000
# hz = 800000
# hz = 75
hz = 60

# RBG => GPIO 17, 27, 22 真实引脚接线对应关系
# rgb => 输出颜色顺序 `绿红蓝` ❌
# ❌ 山寨版 RBG LED
# red = GPIO.PWM(17, hz)
# blue = GPIO.PWM(27, hz)
# green = GPIO.PWM(22, hz)

# BGR => 蓝绿红 ✅, 但是 BCM GPIO 针脚与 RBG 针脚逻辑上完全不符合呀 💩
blue = GPIO.PWM(17, hz)
green = GPIO.PWM(27, hz)
red = GPIO.PWM(22, hz)

print('开始闪烁⏳')
print('GPIO.RPI_INFO =', GPIO.RPI_INFO)
print('GPIO.VERSION =', GPIO.VERSION)
print('clean up GPIO on CTRL+C exit 🎉')

def init():
  for color in ["r", "g", "b"]:
    if(color == "r"):
      red.start((100.0))
      green.start((0.0))
      blue.start((0.0))
    elif(color == "g"):
      red.start((0.0))
      green.start((100.0))
      blue.start((0.0))
    else:
      red.start((0.0))
      green.start((0.0))
      blue.start((100.0))
    sleep(3)
    # sleep(1)

init()

def clear():
  red.stop()
  green.stop()
  blue.stop()
  GPIO.cleanup()


try:
  while True:
    for r in range(11):
      for g in range(11):
        for b in range(11):
          red.start((r * 10.0))
          green.start((g * 10.0))
          blue.start((b * 10.0))
          # print('✅ RGB =', r*10.0, g* 10.0, b*10.0)
          # ValueError: dutycycle must have a value from 0.0 to 100.0
          sleep(0.01)
except KeyboardInterrupt:
  # clear()
  print('结束闪烁 ❌')
finally:
  clear()
  print('结束闪烁 👌🏻')


"""

https://ozeki.hu/p_3047-how-to-setup-a-rgb-led-on-raspberry-pi.html

https://s761111.gitbook.io/raspi-sensor/ba-wan-san-se-ledpwm-hu-xi


https://www.cnblogs.com/xgqfrms/p/17397022.html

https://www.cnblogs.com/xgqfrms/p/17397440.html

"""

#!/usr/bin/env python3
# coding: utf8

from time import sleep
import board
import adafruit_dht

dhtDevice = adafruit_dht.DHT11(board.D17)
# dhtDevice = adafruit_dht.DHT11(board.D18)
# dhtDevice = adafruit_dht.DHT11(board.D18, use_pulseio=False)

print('开始读取温湿度 🌡 💦')

# once
def once():
  try:
    temperature_c = dhtDevice.temperature
    temperature_f = temperature_c * (9 / 5) + 32
    humidity = dhtDevice.humidity
    # print("Temperature: {:.1f} °F / {:.1f} °C".format(temperature_f, temperature_c))
    print("🌡 华氏温度 Temperature: {:.1f} °F ".format(temperature_f))
    print("🌡 摄氏温度 Temperature: {:.1f} °C".format(temperature_c))
    print("💦 湿度 Humidity: {}% ".format(humidity))
  except KeyboardInterrupt:
    print('Ctrl + C 退出 ✅')
  except RuntimeError as error:
    print("error =", error, error.args[0])
    pass
  except Exception as error:
    # dhtDevice.exit()
    raise error
  finally:
    sleep(2.0)
    dhtDevice.exit()
    # cleanup
    print('clear 🚀')

# infinite loop
def infinite():
  while True:
    try:
      temperature_c = dhtDevice.temperature
      temperature_f = temperature_c * (9 / 5) + 32
      humidity = dhtDevice.humidity
      # print("Temperature: {:.1f} °F / {:.1f} °C".format(temperature_f, temperature_c))
      print("🌡 华氏温度 Temperature: {:.1f} °F ".format(temperature_f))
      print("🌡 摄氏温度 Temperature: {:.1f} °C".format(temperature_c))
      print("💦 湿度 Humidity: {}% ".format(humidity))
    except KeyboardInterrupt:
      print('Ctrl + C 退出 ✅')
    except RuntimeError as error:
      print("error =", error, error.args[0])
      pass
    except Exception as error:
      # dhtDevice.exit()
      raise error
    finally:
      sleep(2.0)
      dhtDevice.exit()
      # cleanup
      print('clear 🚀')

once()
# infinite()

"""
https://www.cnblogs.com/xgqfrms/p/17406481.html

https://stackoverflow.com/questions/74167188/get-rid-of-lost-access-to-message-queue-in-a-simple-python-script/76264450#76264450

"""


refs

RPi.GPIO

https://www.cnblogs.com/xgqfrms/p/17374377.html

rpi_ws281x

https://www.cnblogs.com/xgqfrms/p/17387711.html

WS2811_STRIP_GRB

color channel:
GRB => WS2811_STRIP_GRB(RGB LEDs Strip, 3参数)GRBW => WS2811_STRIP_GRBW (RGBW LEDs Strip, 4 参数)

https://www.cnblogs.com/xgqfrms/p/17394537.html

Adafruit CircuitPython NeoPixel All In One

https://www.cnblogs.com/xgqfrms/p/17451650.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-06-02 17:08  xgqfrms  阅读(191)  评论(4编辑  收藏  举报