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

Adafruit CircuitPython NeoPixel All In One

Adafruit CircuitPython NeoPixel All In One

Raspberry Pi & Python & WS2812B RGB LED Strip

neopixel

# install for current user
$ pip3 install adafruit-circuitpython-neopixel

# install system-wide
$ sudo pip3 install adafruit-circuitpython-neopixel

https://pypi.org/project/adafruit-circuitpython-neopixel/

https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel

docs

https://readthedocs.org/projects/adafruit-circuitpython-neopixel/

https://docs.circuitpython.org/projects/neopixel/en/latest/
https://docs.circuitpython.org/projects/neopixel/en/latest/index.html
https://docs.circuitpython.org/projects/neopixel/en/3.1.1/_modules/neopixel.html

API

image

neopixel.GRB= 'GRB'
Green Red Blue

neopixel.GRBW= 'GRBW'
Green Red Blue White

Class:

neopixel.NeoPixel(pin: Pin, n: int, *, bpp: int = 3, brightness: float = 1.0, auto_write: bool = True, pixel_order: str = None)

A sequence of neopixels.

Parameters:
pin (Pin) – The pin to output neopixel data on.

n (int) – The number of neopixels in the chain

bpp (int) – Bytes per pixel. 3 for RGB and 4 for RGBW pixels.

brightness (float) – Brightness of the pixels between 0.0 and 1.0 where 1.0 is full brightness

auto_write (bool) – True if the neopixels should immediately change when set. If False, show must be called explicitly.

pixel_order (str) – Set the pixel color channel order. GRBW is set by default.

https://docs.circuitpython.org/projects/neopixel/en/latest/api.html

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

import neopixel
import board
from time import sleep

# neopixel.NeoPixel(pin: Pin, n: int, *, bpp: int = 3, brightness: float = 1.0, auto_write: bool = True, pixel_order: str = None)
# pixels = neopixel.NeoPixel(board.D18, 60, brightness=0.2, auto_write: False, pixel_order: neopixel.GRB)
pixels = neopixel.NeoPixel(board.D18, 60, brightness=0.2, auto_write: True, pixel_order: neopixel.GRB)

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

import neopixel
import board
from time import sleep

# neopixel.NeoPixel(pin: Pin, n: int, *, bpp: int = 3, brightness: float = 1.0, auto_write: bool = True, pixel_order: str = None)
pixels = neopixel.NeoPixelboard.NEOPIXEL, 60, brightness=0.2, auto_write: False, pixel_order: neopixel.GRB)
pixels = neopixel.NeoPixel(board.NEOPIXEL, 60, brightness=0.2, auto_write: True, pixel_order: neopixel.GRB)

Python 函数参数的传递方式 ???

匿名参数
具名参数

  1. 具名参数前面的参数可以省略参数名
  2. 具名参数后面的参数必须写参数名
#!/usr/bin/env python3
# coding: utf8

def func_args(arg1: int, arg2: str = None, arg3: float = 1.0, arg4: bool = True):
  print("arg1 {}".format(arg1))
  print("arg2 {}".format(arg2))
  print("arg3 {}".format(arg3))
  print("arg4 {}".format(arg4))

# 全部使用匿名参数 ✅
func_args(60, "LEDs", 0.2, False)

# 全部使用匿名参数 ✅
func_args(arg1: 60, arg2: "LEDs", arg3: 0.2, arg4: ,False)

# 混合使用,前面匿名参数,后面具名参数 ✅
func_args(60, "LEDs", arg3: 0.2, arg4: False)

# 混合使用,前面匿名参数,中间具名参数,后面匿名参数 ❌
func_args(60, "LEDs", arg3: 0.2,  False)

Python online REPL

https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3

bugs ❌

https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel/issues/151

https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel/issues/153

demos

Feather M0 Express and Metro M0 Express

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

import board
import neopixel

# 1 LEDs ❓
pixels = neopixel.NeoPixel(board.NEOPIXEL, 1)
pixels[0] = (10, 0, 0)

image

https://www.adafruit.com/product/3403

image

https://www.adafruit.com/product/3505

Circuit Playground Express

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

import board
import neopixel

# 10 LEDs❓
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=False)

pixels[0] = (10, 0, 0)
pixels[9] = (0, 10, 0)

pixels.show()

image

https://www.adafruit.com/product/3333

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

import board
import neopixel

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=False)

# RGB test
pixels[0] = (255, 0, 0)
pixels[1] = (0, 255, 0)
pixels[2] = (0, 0, 255)

pixels.show()

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

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

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

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_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
LED_INVERT = False       # True to invert the signal (when using NPN transistor level shift)
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.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/17452392.html

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



©xgqfrms 2012-2021

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

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


posted @ 2023-06-02 14:17  xgqfrms  阅读(42)  评论(1编辑  收藏  举报