I think it is practically impossible that wrong parameter settings of the serial port would cause it to read extra NUL
characters (b'\x00'
, also called null character) and otherwise read correct data. It looks like your device sends null-terminated records. PuTTY and other terminals do not show NUL
characters.
The following code should resolve the problem. Just add the serial port parameters (baudrate
etc.) as needed, adjust the timeout and you will probably want to collect the received values into a list (your_list.append(value)
).
import serial
with serial.Serial(
port='COM4', timeout=5 # set your parameters as needed, reading timeout 5 seconds
) as ser:
while True:
record = ser.read_until(expected=b'\x00') # read null-terminated record
if not record or record[-1] != 0: # incomplete record read means timeout
break
value = float(record.rstrip(b'\r\n\x00')) # remove CR, LF and NUL at the end
print(value) # do whatever with the value
I tested that float()
can convert directly from bytes
, it treats the characters as ASCII and calling .decode()
is not needed.[1]
-
There is this open issue Explicitly mention bytes and other buffers in the documentation for float() · Issue #77748 · python/cpython · GitHub because documentation does not describe this possibility. ↩︎