1

I have written a UART py-serial script, which looks like.

import serial
import time

try:
     ser = serial.Serial(
     #port='/dev/ttyAMA0',
     port='/dev/ttyUSB1',
     baudrate = 9600,
     parity=serial.PARITY_NONE,
     stopbits=serial.STOPBITS_ONE,
     bytesize=serial.EIGHTBITS,
     timeout=2
    )
    print ('Connection is open : ',str(ser.isOpen()))
except Exception as e:
    print ("Something got wrong: ", e)


ser.write(b'hello..')

and have a similar script as receiver.

what I want is: suppose timeout = 5

ser.write(b'Helloo...')
ser.flush()
ser.readline()

the other script is reading it and sending a response via serial only. this readline should wait maximum for this timeout, if it received response in 2 seconds then it should not wait for 5seconds.

But using this timeout it waits for 2 seconds, even if the data is received in a second.

so my concern is to wait maximum for timeout, but if data received earlier it should end and proceed.

Not able to find this functionality, please help.

Community
  • 1
  • 1
MukundS
  • 527
  • 1
  • 6
  • 11
  • What is your "data"? Does it include an 'end-of-line'? – domen Nov 01 '18 at 09:06
  • @domen, not exactly, but it is not even fixed, can be anything like "{{ key ; value }}" – MukundS Nov 01 '18 at 10:31
  • I don't think that `pyserial` have this functionality inbuilt. To implement this, you can have another software timer running for 2 sec. If there is data before the timer ends, then break the pyserial `read` function. To have more precise control over the data, use single byte read instead of `readline` function. – svtag Nov 01 '18 at 11:35
  • @Sma, can you suggest something or an example would be fine – MukundS Nov 01 '18 at 11:40
  • @Sma, by software time you mean, time.sleep(2)? – MukundS Nov 01 '18 at 11:40
  • 1
    @MukundS, `time.sleep()` is a delay function. It will stall the execution of the program for the specified time (NOTE: it will not affect the serial reading of the PC). You can either use this to stall the program for 2 sec, and then read the serial buffer OR see this answer https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python – svtag Nov 01 '18 at 11:45

1 Answers1

0

found a way for this to work:

pyserial have this inbuit functionality, for eg:

ser.read_until(b'#') #just specify EOL here

It will break if this (#) is found. if not, will wait for timeout and return at end.

You can also use seperate timeouts for read and write:

timeout=5 #read timeout
write_timeout=5 # write timeout
MukundS
  • 527
  • 1
  • 6
  • 11