Search code examples
pythonserial-portwait

Stop waiting for serial response after 5 seconds in Python


I am trying to get a response from a serial port, but sometimes there will be none. This makes my script wait forever, thus I have to kill it.

Is there a simple way to make my code wait for example 5 seconds and if there was no response continue with the script?

My code looks like this:

import serial
ser = serial.Serial('COM3', 9600)

test = '2ho0'

ser.write(str.encode(test))
data = ser.readline()
print(data)

I have tried this solution, but it does not stop after 5 prints of Hello world. Instead, it continues writing Hello World, until I get a runtime error.

Over here and here I tried severeal answers with no success either.

EDIT: I am wondering if it is possible to have something like:

ser.serialReplyAvailable()

This would do the job for me as well.

Thanks for any advice.


Solution

  • You can specify a read timeout which will make the ser.readline() either return immediately if the requested data is available, or return whatever was read until the timeout expired. Check the pySerial docs there is more on this there.

    ser = serial.Serial('COM3', 9600, timeout=5)