[tool] spi ws2812

This commit is contained in:
IrvingGao 2024-06-26 22:35:04 +08:00
parent 274b7235bc
commit 947a031a59
1 changed files with 71 additions and 0 deletions

View File

@ -0,0 +1,71 @@
import wiringpi
import time
# LED灯的数量
LED_N = 8
# GPIO针脚确保这是能够输出PWM信号的针脚比如18
GPIO_PIN = 12
# 初始化WiringPi
wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(GPIO_PIN, wiringpi.OUTPUT)
# 发送单个bit
def sendBit(value, isLastBit=False):
HIGH_TIME_NS = 300 # 高电平时间约为0.3us (300ns),可能需要根据实际情况调整
LOW_TIME_NS = 900 # 低电平时间约为0.9us (900ns)适用于大约1/3的时间为高电平的情况
HALF_PERIOD_NS = HIGH_TIME_NS + LOW_TIME_NS
if value:
wiringpi.digitalWrite(GPIO_PIN, 1)
time.sleep(HIGH_TIME_NS / 1000000)
else:
wiringpi.digitalWrite(GPIO_PIN, 0)
time.sleep(HIGH_TIME_NS / 1000000)
wiringpi.digitalWrite(GPIO_PIN, 0)
if not isLastBit:
time.sleep(LOW_TIME_NS / 1000000)
# 发送颜色到指定的LED
def sendColor(r, g, b):
for _ in range(3):
sendBit(True) # 开始位
sendByte(r)
sendByte(g)
sendByte(b)
for _ in range(2):
sendBit(True) # 结束位
def sendByte(value):
for bit in range(8):
sendBit((value >> (7 - bit)) & 1)
def refreshLEDs():
for led in range(LED_N):
sendColor(0, 0, 0) # 先熄灭所有LED
time.sleep(50/1000000) # 留一些时间间隔
for led in range(LED_N):
# 这里简化为只用红色演示,可根据需要修改为其他颜色
sendColor(171, 31, 120) # 浅蓝色,亮度调低
def chaseColor():
global LED_N
count = 0
while True:
count = (count + 1) % LED_N
for i in range(LED_N):
if i == count:
sendColor(171, 31, 120) # 当前LED亮浅蓝色
else:
sendColor(0, 0, 0) # 其他LED熄灭
time.sleep(0.1) # 等待一段时间再改变下一个LED
try:
chaseColor()
except KeyboardInterrupt:
print("程序中断,清理工作...")
finally:
wiringpi.digitalWrite(GPIO_PIN, 0) # 清理工作确保GPIO输出为0
wiringpi.pinMode(GPIO_PIN, wiringpi.INPUT)