Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding characters received from Arduino

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 :)

like image 660
Gaztelu Avatar asked Apr 27 '13 09:04

Gaztelu


People also ask

How do I find a character in a string Arduino?

In order to check if a specific substring exists within a string in Arduino, the indexOf() function can be used. This returns the index of the first occurrence of the character or a string that you are searching for within another string.

How does Arduino send serial data?

Description. Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the print() function instead.


2 Answers

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?
like image 94
Jonathon Reinhart Avatar answered Oct 12 '22 02:10

Jonathon Reinhart


You can also use decode() and strip() at once.

b'20.32\r\n'.decode().strip('\r\n')

Will give you:

'20.32'
like image 38
goetzc Avatar answered Oct 12 '22 04:10

goetzc