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','rn']
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/Padraic and Oscar who provided Answers I can give an update on how to fix the above problem. I prefer Johsn solution, slightly more elegant, but either work. I added the following:
John's/Pad solution (see answers below for better and more detail):
sInput = oSer.readline().strip()
Oscars solution:
if (len(lsInput) > 3): # this is to help with the first line of serial input which is often full of errors
(a,b,c,d) = lsInput # as shown above the serial communication returns a funny last term, my guess it has something to do with the println on the arduino side
aint = int(a) # is now possible
Aucun commentaire:
Enregistrer un commentaire