Reputation: 143
I'm reading a value through Python from the serial port of a sensor of Arduino.
My code(Python):
arduino = serial.Serial(2, 9600, timeout=1)
print("Message from arduino: ")
while True:
msg = arduino.readline()
print(msg)
I don't know why the output result is something like b'[sensor-value]\r\n'
.
So, I get something like b'758\r\n'
b'534\r\n'
b'845\r\n'
etc (regarding to sensor change value).
How I convert this?
Upvotes: 6
Views: 35053
Reputation: 189
Encountered a similar problem with a Raspberry Pi Pico where I needed to both decode and get rid of the extra characters. That can all be achieved with a one-liner. This relies on the pySerial
package.
msg = ser.readline().decode('utf-8').rstrip()
For the above example, serial.Serial
has been named arduino
instead of ser
, so the solution there would simply be:
msg = arduino.readline().decode('utf-8').rstrip()
Found the hint in this blog post.
Upvotes: 0
Reputation: 1112
You need to decode it.
print(msg.decode('utf-8'))
Please check Lexical Analysis on Python 3 documentation to see what string prefixes means
Upvotes: 11