I'm setting up a robust protocol to read data (from accelerometer) from an Arduino board via serial port with Python. I am using Python 3.4 at the moment, but I could go back to a previous version.
Now, the code is working until I shake the accelerometer a lot. At which point I receive this error:
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
>>>
I used this solution and adapted it to Python 3.4 (added b infront of the \n character):
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]
The data are sent by the board in a simple format (Arduino Code):
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");
I assume that my protocol is not robust or I made some error in the parsing, but I can't figure it out. Thanks a lot for help, Michele