为何非9600波特率会导致Python与Elegoo Uno串口通信数据损坏?
Spotify WS2811灯带同步项目问题求助
我正在开发一个将WS2811可寻址灯带与Spotify同步的个人项目,无需实时音频分析。Python程序读取JSON文件,根据歌曲播放进度确定哪些LED应切换为指定颜色。
JSON格式说明
{ "0": [[0,4,0,0,255], [5,6,255,0,0]], "1832": [[0,0,255,0,0]]}
键代表歌曲播放的毫秒时间戳。每个数组中前两个值为LED索引范围,后三个为RGB值。例如"0":[[0,4,0,0,255], [5,6,255,0,0]]表示:在0毫秒时,将LED 0至4设为蓝色,LED 5至6设为红色。
当前项目状态
- 目前索引范围逻辑尚未完成,前两个值始终相等(即每个5字节数组仅控制单个LED)
- 即使仅处理10个LED,已出现明显延迟,后续扩展到300+LED时性能会极差
Python代码
for timestamp in led_data.keys(): if last_sent_timestamp < timestamp <= elapsed_time: message = bytearray([]) for values in led_data[timestamp]: message.append(254) # Start byte led_index_1, led_index_2, r, g, b = values message.extend([led_index_1, led_index_2, r, g, b]) message.append(253) # End byte ser.write(message) ser.flush() last_sent_timestamp = timestamp
Arduino代码
#include <FastLED.h> #define NUM_LEDS 60 #define DATA_PIN 6 #define START_BYTE 254 #define END_BYTE 253 CRGB leds[NUM_LEDS]; void setup() { FastLED.addLeds<WS2811, DATA_PIN, BRG>(leds, NUM_LEDS); FastLED.clear(); FastLED.show(); Serial.begin(9600); } void loop() { static byte buffer[7]; // Buffer to hold the incoming packet static int index = 0; while (Serial.available() >= 7) { byte incomingByte = Serial.read(); if (incomingByte == START_BYTE) { index = 0; // Reset buffer index } buffer[index++] = incomingByte; if (index == 7 && buffer[6] == END_BYTE) { // Complete packet received int ledIndex1 = buffer[1]; int ledIndex2 = buffer[2]; // Useless for now int r = buffer[3]; int g = buffer[4]; int b = buffer[5]; if (ledIndex1 < NUM_LEDS) { leds[ledIndex1] = CRGB(r, g, b); // Changing a single LED rather than a range for now } index = 0; // Reset buffer for the next packet } } FastLED.show(); delay(1); }
波特率相关问题
- 使用9600波特率时无数据损坏,但发送大量数据或连续时间戳时延迟过高
- 切换至57600、115200等波特率后,出现严重数据损坏:LED常显示错误颜色(但索引无误)
- 已完成的排查操作:
- Python端设置
ser = serial.Serial('COM9', 115200) - Arduino端设置
Serial.begin(115200) - 设备管理器修改对应端口波特率
- 更换USB线缆和电脑,问题依旧
- Python端设置
请问我哪里操作有误?
TLDR:ser.write导致程序延迟过高,但提高波特率会引发数据损坏。
内容的提问来源于stack exchange,提问作者Edouard Marsolais
相关产品推荐
相关产品推荐

