Arduino-Python 稳健串行通信协议

2 投票
1 回答
2963 浏览
提问于 2025-04-18 13:13

我正在设置一个可靠的协议,通过串口用Python从Arduino板读取加速度计的数据。现在我使用的是Python 3.4,但我可以回到之前的版本。

目前代码运行正常,直到我大幅度摇动加速度计。这时我收到了这个错误:

b'\xf08\xf8\x15\xf8\xf3|\xf0\x15N\xe8\xf7'
(14576, 5624, -3080, -3972, 19989, -2072)
b'<8\xb0\x08\xdc\x1cY\xed$Sb\xf1'
(14396, 2224, 7388, -4775, 21284, -3742)
b'\xac&\xbe\xedRA\xdc\xf2'
Traceback (most recent call last):
  File "C:\Python34\test_4_serial.py", line 57, in <module>
    pacchetti=unpack('hhhhhh', last_received)
struct.error: unpack requires a bytes object of length 12
>>> 

我使用了这个解决方案并将其调整为适应Python 3.4(在\n字符前加了b):

from serial import *
from struct import *
from threading import Thread
__name__ =  '__main__'
last_received = ''


ser = Serial(
    port='com4',
    baudrate=115200,
    bytesize=EIGHTBITS,
    parity=PARITY_NONE,
    stopbits=STOPBITS_ONE,
    timeout=0.1,
    xonxoff=0,
    rtscts=0,
    interCharTimeout=None
)


ser_buffer=b''
while True:
    temp=ser.read(ser.inWaiting())
    if temp:
        ser_buffer=ser_buffer+temp                        
        if b'\n' in ser_buffer:

            lines = ser_buffer.split(b'\n') # Guaranteed to have at least 2 entries
            last_received = lines[-2]
            print(last_received)
            pacchetti=unpack('hhhhhh', last_received)
            print(pacchetti)
            ser_buffer = lines[-1]   

数据是由板子以简单的格式发送的(Arduino代码):

        Serial.write((uint8_t)(ax & 0xFF));Serial.write((uint8_t)(ax >> 8)); 
        Serial.write((uint8_t)(ay & 0xFF));Serial.write((uint8_t)(ay >> 8)); 
        Serial.write((uint8_t)(az & 0xFF));Serial.write((uint8_t)(az >> 8)); 
        Serial.write((uint8_t)(gx & 0xFF));Serial.write((uint8_t)(gx >> 8)); 
        Serial.write((uint8_t)(gy & 0xFF));Serial.write((uint8_t)(gy >> 8)); 
        Serial.write((uint8_t)(gz & 0xFF));Serial.write((uint8_t)(gz >> 8)); 

        //Serial.write("\r");
        Serial.write("\n");

我认为我的协议不够可靠,或者在解析时出了些问题,但我搞不清楚具体是什么。非常感谢大家的帮助,米凯尔

1 个回答

0

看看这个链接:

https://kentindell.wordpress.com/2015/02/18/micrcontroller-interconnect-network-min-version-1-0/

这是一个非常可靠的协议,它使用一种叫做“字节填充”的技术来标记数据帧的开始。这样,如果接收方的状态出现了问题,它会自动在正确的位置重置。这个链接里还有一个用Python写的实现,以及一个可以在Arduino和电脑上运行的“你好,世界”程序。

撰写回答