4

Sometimes I do not get any data in via the serial interface and I want to catch this case with an exception in the following way:

ser          = serial.Serial(3)
ser.baudrate = 115200
timeout      = 1

while (some condidion)
  try:
    dump = ser.read(40)
  except ser1.SerialTimeoutException:
    print('Data could not be read')

ser.close()

However, when I run this program, the exception is never caught when no data is in the buffer and I am stuck in an endless loop. Anyone an idea what I am doing wrong here?

3
  • 1
    Two things that may be typos / omissions in question code: 1. exception should probably be serial.SerialTimeoutException 2. you do not set the condition to False after catching the exception. Commented Jun 11, 2012 at 10:23
  • Do you ever see the message "Data could not be read"? Commented Jun 11, 2012 at 10:37
  • Nope, never saw it because the exception got never caught as glglgl explains below! Commented Jun 11, 2012 at 12:47

1 Answer 1

7

I didn't even know about that exception. After having a look at the API documentation, you'll see that this exception only applies to write().

If you read(), you'll just have a shortened or even empty output.

And this applies only if you have opened the connection with a timeout. Something like serial.Serial(3, timeout=.1).

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

1 Comment

brilliant, exactly what I was looking for. Works now ;)

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.