I am using Arduino SoftwareSerial library to send serial data to a Raspberry Rx pin. I can get the Arduino serial data sent over to the Raspberry successfully, in as much that the integers I sent arrive as the equivalent in a string.
The problem:
I am trying to convert the string that the .readline() returns into a float or int, but I am unable to do so.
import serial
oSer = serial.Serial("/dev/ttyAMA0",baudrate=57600,timeout=1)
while True:
sInput = oSer.readline()
print sInput #Returns: >>1,2,3,
lsInput = sInput.split(',')
print lsInput #Returns: >>['1','2','3','\r\n']
How can I convert this to an int or float? I simply need to do some arithmetic with the numbers. I have tried:
lfInput = [float(i) for i in lsInput] #Returns: >> ValueError: could not convert to float:
liInput = [int(i) for i in lsInput] #Returns: >> ValueError: invalid literal for int() with base 10: ''
The Answer
Thanks to John and Padraic who provided Answers, I can confirm an update on how to fix the above problem. I prefer Padraic's solution, slightly more elegant, but either work. I added the following:
John's and especially Pad's solution (see answers below for better and more detail):
sInput = oSer.readline().strip() #but see answers below from Pad for more detail
解决方案
The error is caused by the \r\n at the end of the line. int() and float() don't like that.
You can either strip it off like so:
sInput = oSer.readline().strip()
Or you can modify the loop to ignore non-numbers:
liInput = [int(i) for i in lsInput if i.isdigit()]