1

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.

X_841
  • 191
  • 1
  • 14
  • I think the asyncio module (specificaly the `Task` class) is what you're looking for. This can help: https://stackoverflow.com/questions/34710835/proper-way-to-shutdown-asyncio-tasks – Er... Nov 28 '19 at 10:35
  • I thought that `SIGNAL` only works correctly on unix. Since I am on Windows, this is unfortunately not working. I get the error `signal has no attribute SIGHUP`. – X_841 Nov 28 '19 at 10:54

2 Answers2

2

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)

FlyinDoji
  • 63
  • 7
0

You could try wrapping the readline into a while Statement and have a timer tick inside if the reading was not successful. If it is, break out of it.

from time import sleep
tries = 0
while tries < 4:
    data = ser.readline()
    if data != None: #Or "", whatever the return data
        break
    sleep(5); tries += 1
tst
  • 371
  • 1
  • 11
  • This does not help since the script is stuck at `data = ser.readline()`. – X_841 Nov 28 '19 at 10:49
  • ah, so you are not getting "None" returned, you just get no response at all. That is indeed more tricky. The only thing I can think of is maybe if you use a new thread and then shut that down after a certain amount of time has passed? – tst Nov 28 '19 at 11:29