Trying to read data from sensor over serial port and then plot – cannot convert string to float

Issue

I’m using pyserial to read data from a sensor on COM6. I used Serial.println() in the Arduino module of the embedded chip that hosts the sensor to push the data to the serial port.

When I monitor the serial port, I can see the data being pushed and it is in the range:
-1.00 to 500.00

In my Python script, I open the port, then read from the port but when I try to cast the strings received to float I receive an error that I cannot do it…

Snippets from code :

s = serial.Serial(
      port='COM6',
      baudrate=57600,
      parity=serial.PARITY_NONE,
      stopbits=serial.STOPBITS_ONE,
      bytesize=serial.EIGHTBITS,
      timeout=1
)


# Define what we want to graph
x = 0;
while x < 1000:
    a=s.readline()
    a.decode()
    y=float(a)
    plt.plot(x,y)
    plt.ylabel("Pressure")
    plt.xlabel("Time")
    x=x+1

error:

ValueError: could not convert string to float: b'--1.80\r\n'

What am I missing please?

Solution

Your problem is that you’re receiving a binary string and not really a number. You first need to decode it and then manipulate to extract the actual number.

Assuming you receive only negative numbers as b'--x.xx\r\n' and positive numbers b'xxx.xx\r\n' you can convert them into float as

a = a.decode()
if a[0] == '-':
   my_float = float(a[1:].strip())
else:
   my_float = float(a.strip())

Answered By – NicoCaldo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published