Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 :)

share|improve this question
1  
Looks like there's a carriage return \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
1  
check the documentation. You should be using the universal newline mode and strip \n's prior to the integer conversion – iruvar Dec 3 '15 at 18:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.