Arduino Mega 2560 to Python Serial Communication Reads Every Other Byte

I am trying to send a list of bytes from Arduino Mega 2560 to Python.

This is the section of Python code receiving the data stream:

def run(self):
   print("Opening %s at %u baud" % (self.portname, self.baudrate))
   try:
      self.ser = serial.Serial(self.portname, self.baudrate, timeout=SER_TIMEOUT, parity=serial.PARITY_ODD)
      time.sleep(SER_TIMEOUT*1.2)
      self.ser.reset_input_buffer()
   except:
      self.ser = None
   if not self.ser:
      print("Can't open port")
      self.running = False
   while self.running:
      s = self.ser.read(size=1)
      print(s)
   if self.ser:
      self.ser.close()
      self.ser = None

This is the section of Arduino code writing the bytes to the serial port:

byte data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
for (int i=0; i<9; i++) {
   Serial.write(data[i]);
   Serial.write(0x00);
}

This gives the output I'm expecting:

b'\x00'
b'\x01'
b'\x02'
b'\x03'
b'\x04'
b'\x05'
b'\x06'
b'\x07'
b'\x08'

If I remove the line in the Arduino code that's adding zero bytes between every value (Serial.write(0x00);), I get the following output in Python:

b'\x00'
b'@'
b'\xa0'
b'\x04'
b'A'
b'\xd0'
b'\x08'

I don't want to be sending extraneous data but despite hours of looking online and at the code I can't figure out why python is reading the data like this. To my understanding, setting the read size=1 should mean that the data is read one byte at a time. Is python expecting 16-bit values? Is the issue in the way Arduino is transmitting data? Or am I missing something simple?

The default configuration of your Serial port on arduino is 8 data bits, no parity, one stop bit

Try with PARITY_NONE or just set the baud rate and use the pyserial defaults

Yes! Thank you so much, I knew it'd be something small.

Have fun !

Note you can send your array in just one write passing the pointer to the first element and the size, no need for the for loop

Thanks! New to arduino serial transmission (clearly haha) and for the sake of testing I switched out the data I'm actually sending with that short array and needed the for loop to shove the zeros in between... totally would've missed cleaning that up
Thanks again for the super quick reply!

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.