1

I'm writing some code to read from a serial interface and return the integer value of the data received.

It seems that i need to remove the "\r\n" from it. I tried splitting, but it doesn't work.

Here's my code:

import time
import serial
import string         

ser = serial.Serial(
    port='/dev/ttyACM1',
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
)
counter = 0

while 1:
    x = ser.readline()

    if "t" in x:
        print x
        x = int(x)
        print x
        print "temp"
    elif "h" in x:
        print  "hum "
    elif "g" in x:
        print  "gas "
    else:
        pass

    time.sleep(1)

Then I have this error:

 Traceback (most recent call last):
  File "/home/pi/read.py", line 26, in <module>
    x=int(x)
ValueError: invalid literal for int() with base 10: 't0\r\n'

Could anyone help?

2
  • 3
    you need to remove the letters, the t is what cause your problem Commented Jul 11, 2016 at 5:23
  • 1
    Error is clear - input string cannot be converted to int (since there is "t" in string, how would you convert it to int unambiguously?) You need to do some kind of pre-processing on t before attempting to convert it. What kind of processing? I'll let you figure it out yourself. Commented Jul 11, 2016 at 5:33

1 Answer 1

1

Try it like this:

import time
import serial
import string         

ser = serial.Serial(
    port='/dev/ttyACM1',
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
)
counter = 0

while True:
    line = ser.readline().rstrip()
    if not line:
        continue

    resultType = line[0]
    data = int(line[1:])

    if resultType == 't':
        print "Temp: {}".format(data)
    elif resultType == 'h':
        print "Hum: {}".format(data)
    elif resultType == 'g':
        print "Gas: {}".format(data)
    else:
        pass

    time.sleep(1)

The first change is to str.rstrip() the line we read from the serial interface. This removes any "\r\n" characters or whitespace from the end of the string. The second change is to split the line into the "type" letter (line[0]), and the data (the rest of the line).

Sign up to request clarification or add additional context in comments.

2 Comments

Traceback (most recent call last): File "/home/pi/read.py", line 18, in <module> resultType = line[0] IndexError: string index out of range
The exact same error? Can you show me the error message? Is the "type" always a single letter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.