Python Forum

Full Version: Convert string to float problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I have a problem converting a string to a float. The program receives data from Arduino via the serial port and processes it. But I'm getting this error message. Is there a solution? Thank you!

from pynput.mouse import Button, Controller
import time
import serial

mouse = Controller()
ser = serial.Serial('COM3', baudrate=9600, timeout=1)


while True:
    arduinoData = ser.readline().decode('ascii')
    print(arduinoData)
    data = (float(arduinoData))
    mouse.position = (data, 100)
The string is empty. What should your program do in that case? You can catch the exception and set whatever value you want when that happens, or do something else.
If you don't get get data within 1 second the read gives up and returns an empty buffer. It is possible that you could also time out while reading data and get a partial buffer. You might also get a transmission error that results in bad data. I would cover all three possibilities by wrapping an exception handler around the conversion and only updating the mouse position when you successfully read a new value.
Arduino sends data with a delay of 1 ms.
This is how output and Arduino code looks like.
Oh, thank you. It works perfectly with try/except! Also I have one more question. I need to make value bigger (multiply), but this does not work. How can I do it?

from pynput.mouse import Button, Controller
import time
import serial

mouse = Controller()
ser = serial.Serial('COM3', baudrate=9600, timeout=1)


while True:
    try:
        arduinoData = ser.readline().decode('ascii')
        data = (arduinoData)/5
        print(data)
        mouse.position = (data, 100)
    except:
        print("fail")
        break
EDIT: Solved also this.
Where is float()?
(May-28-2022, 01:08 PM)deanhystad Wrote: [ -> ]Where is float()?
Program doesnt end with error anymore so I donĀ“t need it.
This gets a str object:
arduinoData = ser.readline().decode('ascii')
This tries to divide the str by 5
data = (arduinoData)/5
Dividing a str by an int raises a TypeError which is caught by the overly broad except: Your program prints "fail" every time, no matter what is read
You should do this:
data = float(arduinoData)/5
This might also fail, but if arduinoData is a string that can be interpreted as a float, it will succeed.