Could not convert string to float: Python code for a pH meter

98 Views Asked by At

I'm new to coding and am attempting to build a pH meter with pre-written code for the GUI. I've double checked all connections in my instrument, but the python code is the last thing crashing. When I try and run the instrument, I get this error:

    Traceback (most recent call last):
    File "C:\Users\livst\sensors.py", line 353, in updateFigs
    self.data = [float(val) for val in line.split()] # split data to 
    float numbers
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\livst\sensors.py", line 353, in <listcomp>
    self.data = [float(val) for val in line.split()] # split data to 
   float numbers
             ^^^^^^^^^^
    ValueError: could not convert string to float: b'Read'

After some reading, I attempted to decode the string using text.decode("utf-8") and by using text.encode("windows-1252").decode("utf-8").

When I use these commands, I get the same error with different text in the ValueError:

Traceback (most recent call last):
  File "C:\Users\livst\sensors.py", line 353, in updateFigs
    self.data = [float(val) for val in line.split()] # split data to float numbers
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\livst\sensors.py", line 353, in <listcomp>
    self.data = [float(val) for val in line.split()] # split data to float numbers
                 ^^^^^^^^^^
ValueError: could not convert string to float: b'H\xf4Read'

This is the portion of code it is referring to in the error:

def updateFigs(self):
        line = self.ser.readline() # read data from serial port, one line at a time
        self.data = [float(val) for val in line.split()] # split data to float numbers
        # the data read from the serial port should be 4 float numbers, otherwise neglect it.
        # the 4 float numbers are temperaure, humidity, voltage at reference electrode,
        # and voltage at pH electrode, respectively.
        line.decode("utf-8")
        if(len(self.data) == 4):
            self.temp_lcd.display(self.data[0])
            self.temp_plot.y = np.append(self.temp_plot.y, float(self.data[0]))
            self.temp_plot.y = np.delete(self.temp_plot.y, 0)
            self.temp_plot.li.set_ydata(self.temp_plot.y)
            self.temp_plot.axes.set_ylim(min(self.temp_plot.y)-1, max(self.temp_plot.y)+1)
            self.temp_plot.draw()

The GUI opens, but I can't collect data yet. How can I resolve this?

1

There are 1 best solutions below

1
On

Check val before parsing.

self.data = [float(val) for val in line.split() if val.isnumeric()]