I am trying to read a line of serial data from a MaxBotix sonar sensor with Python.
The sensor spits out R0300
The integers after the "R" are the distance read in millimeters. I am trying to write a script that removes the "R" and converts the string into an integer. I successfully removed the "R" but when I try to convert the string into an int I get this error: ValueError: invalid literal for int() with base 10: '1187\r1187\r1188\r1188\r1188\r1188\r1188\r1188\r1188\r1188\r1188\r1189\r1189\r1189\r1189\r1189\r118'
I'm new to Python, here is the code:
import serial
from time import sleep
mmtoinch = 25.4
#print ser.isOpen() #to check port is open
ser = serial.Serial('/dev/ttyAMA0', 9600)
try:
while True:
rawdata = ser.readline(100)
#Removing the "R" from the Range Finder output
intconversion = rawdata.replace("R","")
#print(rawdata)
intconversion.replace(" ","")
print(intconversion)
intrange = int(intconversion)
sleep(1)
except KeyboardInterrupt:
print ' end'
Indentation may be wrong. Any help is greatly appreciated! Thank you in advance :)
\r
confusing the integer conversion? Maybe try splitting on those, or using a regular expression to get just the digits? – thrig Dec 3 '15 at 17:47\n
's prior to the integer conversion – iruvar Dec 3 '15 at 18:25