Question

I am trying to read a line from serial connection and convert it to int:

print arduino.readline()
length = int(arduino.readline())

but getting this error:

ValueError: invalid literal for int() with base 10: ''

I looked up this error and means that it is not possible to convert an empty string to int, but the thing is, my readline is not empty, because it prints it out.

Was it helpful?

Solution

The print statement prints it out and the next call reads the next line. You should probably do.

num = arduino.readline()
length = int(num)

Since you mentioned that the Arduino is returning C style strings, you should strip the NULL character.

num = arduino.readline()
length = int(num.strip('\0'))    

OTHER TIPS

Every call to readline() reads a new line, so your first statement has read a line already, next time you call readline() data is not available anymore.

Try this:

s = arduino.readline()
if len(s) != 0:
    print s
    length = int(s)

When you say

print arduino.readline()

you have already read the currently available line. So, the next readline might not be getting any data. You might want to store this in a variable like this

data = arduino.readline()
print data
length = int(data)

As the data seems to have null character (\0) in it, you might want to strip that like this

data = arduino.readline().rstrip('\0')

The problem is when the arduino starts to send serial data it starts by sending empty strings initially, so the pyserial picks up an empty string '' which cannot be converted to an integer. You can add a delay above serial.readline(), like this:

while True:
    time.sleep(1.5)
    pos = arduino.readline().rstrip().decode()
    print(pos)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top