0

I am trying to write a script currently I am using ser.read() directly and printing values but I want to write a function where it waits for some time reads all char and than gets out of loop. Current loop prints all char but doesnt get out of the loop and I have to either edit and make it exit by keyboard click. But I want a script where it reads and exit and user doesnt need to do anything. Sorry if a noob question but new with Python and Pyserial

if(ser.isOpen()):
    try:
def read():
    ser.flushInput()    
    while 1:
    try:
        check = ser.read()
        print check
    except Exception:
        print("Error")
else:
    print("Port not open")
  • pyserial has a `read timeout` in `__init__` and a `read(size=n)` See: https://pyserial.readthedocs.io/en/latest/pyserial_api.html# – Rolf of Saxony Jun 06 '18 at 14:59
  • https://stackoverflow.com/questions/17553543/pyserial-non-blocking-read-loop – Rolf of Saxony Jun 06 '18 at 15:03
  • Thanks I tried using this but it wont work in python 2.7 and I tried in python 3.x its giving some other errors need to check that but if it works its great while (True): if (ser.inWaiting()>0): #if incoming bytes are waiting to be read from the serial input buffer data_str = ser.read(ser.inWaiting()).decode('ascii') #read the bytes and convert from binary array to ASCII print(data_str, end='') Thanks – embedded_systems_boy Jun 06 '18 at 16:44

1 Answers1

0

If you want to wait for a certain amount of time before exiting, try something like this. In this example, the code will wait for 5 seconds.

import time

def read():
    ser.flushInput()
    start_time = time.time()
    while time.time() - start_time < 5:
        try:
            check = ser.read()
            print check
        except Exception:
            print("Error")
jgrant
  • 1,273
  • 1
  • 14
  • 22
  • Hi jgrant I am using above function but it still stays in loop I am not able to get out of it? Is there any workaround or changes I need to make other than this ? thanks!! – embedded_systems_boy Jun 06 '18 at 16:42
  • My guess is it's hanging on the ser.read() line. It's likely waiting for a byte to be transmitted. Try adding a timeout to ser when you create it. Like this: ser = serial.Serial('COMX', timeout=1) – jgrant Jun 06 '18 at 19:26
  • Thanks jgrant appreciate your help with try it with timeout and hopefully it will work if not I was thinking to use just this part as its working def read(): if(ser.inWaiting() > 0): str = ser.read(ser.inWaiting()) print(str) – embedded_systems_boy Jun 07 '18 at 18:04