2

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.

2
  • what's the output of print arduino.readline()? Commented Mar 30, 2014 at 17:21
  • The problem is when you call readline() in print it consumes the contents and therefore successive call will be empty. Commented Mar 30, 2014 at 17:21

4 Answers 4

3

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'))    
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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

5 Comments

I am getting now this error= ValueError: null byte in argument for int(). Do I need to add a null byte character at the end ?
@pattex007 What does the print statement print?
@pattex007: Strip the null character. data.strip('\0'). Arduino returns C style strings, I think.
this is the code for sending data uartPutData( "16", sizeof(FINAL_LENGTH)); and for output: 16
@pattex007 Just try the suggestion given by Sukrit
1

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)

Comments

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.