Python serial read corrupting print statements
Question:
I have this bizarre situation where reading from a serial port is appearing to corrupt calls to print
. This code:
ser = serial.Serial('COM13', 115200, timeout=5)
ser.reset_input_buffer()
ser.reset_output_buffer()
ser.write("statn".encode('utf-8'))
ser.flush()
for i in range(10):
print(f"read: <{self.ser.read(10).decode('utf-8')}>")
outputs
>ead: <s
read: <
>
read: <>
read: <>
read: <>
...
How can that first ‘>’ be printed by python the first time instead of the r
of read
?!
If I replace the serial calls with just a string, the behaviour is no longer seen .
Answers:
A wild guess is that you’re getting a “carriage return” character (ASCII 13) from the serial port — that would cause the terminal to jump back to the leftmost position. Try adding a !r
to the end of the {}
block in the f-string, so that it prints the repr of the string (or just omit the .decode(...)
so that the undecoded byte array gets printed); that should make it obvious if there are any unprintables in there.
I have this bizarre situation where reading from a serial port is appearing to corrupt calls to print
. This code:
ser = serial.Serial('COM13', 115200, timeout=5)
ser.reset_input_buffer()
ser.reset_output_buffer()
ser.write("statn".encode('utf-8'))
ser.flush()
for i in range(10):
print(f"read: <{self.ser.read(10).decode('utf-8')}>")
outputs
>ead: <s
read: <
>
read: <>
read: <>
read: <>
...
How can that first ‘>’ be printed by python the first time instead of the r
of read
?!
If I replace the serial calls with just a string, the behaviour is no longer seen .
A wild guess is that you’re getting a “carriage return” character (ASCII 13) from the serial port — that would cause the terminal to jump back to the leftmost position. Try adding a !r
to the end of the {}
block in the f-string, so that it prints the repr of the string (or just omit the .decode(...)
so that the undecoded byte array gets printed); that should make it obvious if there are any unprintables in there.