Understanding characters received from Arduino

arduino, pyserial, python

Solution

The `b` prefix in Python 3 just means that it is a `bytes` literal. It's not part of the output, that's just telling you the type.

The `\r\n` is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling `strip()`.

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print 'New value is {0:0.2f}'.format(value)

See also:

- What does the 'b' character do in front of a string literal?

Problem

I have an Arduino board sending data through a serial port and a Python piece of code reading that data. The Arduino board just sends the temperature it reads from a TMP36 sensor and when I check the port using the port monitor that comes with the Arduino IDE I see this: ``` 20.3 20.3 20.2 20.2 ... ``` Which is perfectly correct. Now, when I read the serial port using Python I get this: ``` b'20.32\r\n' b'20.32\r\n' b'20.32\r\n' b'20.80\r\n' ... ``` What does that b' ' thing do? How can I treat the string so I just display the numbers correctly? Here is the code I'm using: ``` import serial ser = serial.Serial('/dev/ttyACM0', 9600) while True: message = ser.readline() print(message) ``` Apologies if it's a dumb question but I'm new to Arduino, Python and serial programming :)

Original source

Related problems