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)