Arduino Python健壮串行通信协议

Arduino Python健壮串行通信协议,python,serial-port,arduino,protocols,Python,Serial Port,Arduino,Protocols,我正在建立一个健壮的协议,通过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, 738

我正在建立一个健壮的协议,通过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
>>> 
数据由电路板以简单格式发送(Arduino代码):

我假设我的协议不是健壮的,或者我在解析过程中犯了一些错误,但我无法理解。 非常感谢你的帮助, 米歇尔

看看:


这是一个健壮的协议,它使用字节填充来标记帧的开始,因此如果接收器不同步,它会自动在正确的点重置。那里还有一个Python实现,还有一个在Arduino和PC上运行的“hello world”程序。

谢谢!我一有时间就去看看:)再见,米歇尔
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]   
        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");