I am trying to get Serial data from my Arduino to my python console
Here is my Arduino code:
void setup() {
Serial.begin(115200);
Serial.setTimeout(10);
randomSeed(analogRead(0));
}
void loop() {
float x = float(random(0,200))/100;
Serial.println(x);
}
I need to get the random variables to my python program. For this i am using Pyserial.
Here is my Python program
import serial
ser = serial.Serial('/dev/ttyACM0',baudrate=115200,timeout=0.1)
ser.flushInput()
while 1:
sens = ser.read(ser.inWaiting())
sens = sens[0:len(sens)-2].decode("utf-8")
print(float(sens))
I am then presented with an Error ValueError: could not convert string to float:
I have tried solving this in multiple ways with no solution. The problem is at the conversion float(sens)
. I need this data as a float for other operations.
Just to check i ran some changes in the code as such
sens = ser.read(ser.inWaiting())
print(sens,end="\t")
print(type(sens))
sens = sens[0:len(sens)-2]
print(sens,end="\t")
print(type(sens))
sens = sens.decode("utf-8")
print(sens,end="\t")
print(type(sens))
And the output i got was
b'1.89\r\n' <class 'bytes'>
b'1.89' <class 'bytes'>
1.89 <class 'str'>
As you can see the final variable is a string and it is what i get when i run sens = sens.decode("utf-8")
. Yet i still cannot get float data from this string when i run float(sens)
Any workaround or solution to this? I am completely lost.
Edit1: I ran
>>> float(b'1.80\r\n')
1.8
in another python console and it works completely fine. What's the problem when it is pyserial read ?
Try this, if you still having problems, please print value before try cast
Consider to use .strip() to clean input value
b = b'1.89\r\n'
float(b.strip())
float("10") --> 10.0
float("10.2") --> 10.2
float("10,2") --> #CRASH ValueError: invalid literal for float(): 10,22
#SOLUTION
float("10,22".replace(",", ".")) --> 10.22
Conclusion
float(b.strip().replace(",", "."))
After looking at this for a long time, i found out that initially for a few iterations, the Arduino was sending NULL data. Or rather it was sending b''
serially. And THIS was the issue.
I am now sure since i checked this in a python console.
>>> float(b'1.0')
1.0
>>> float(b'')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
So to overcome this, all i had to do is a simple comparison during every iteration. such as
if sens != b'':
continue
else:
break
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.