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 :)
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.
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.
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:
You can also use decode()
and strip()
at once.
b'20.32\r\n'.decode().strip('\r\n')
Will give you:
'20.32'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With