Python Forum
Waiting for input from serial port, then move on - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Waiting for input from serial port, then move on (/thread-40936.html)



Waiting for input from serial port, then move on - KenHorse - Oct-16-2023

Why doesn't this leave the while loop?


#wait for % and then move on
indata = ""
Counter = 0
while indata != "%":  
  indata = ser.read()
  print(indata)
  Counter +=  1
  if Counter > 5:
   sys.exit("Timed out waiting for Bootloader Active Character. Please close window and try again")
Result:

b''
b''
b'%'
b'%'
b'%'
b'%'
Timed out waiting for Bootloader Active Character. Please close window and try again


RE: Waiting for input from serial port, then move on - deanhystad - Oct-16-2023

serial port reads bytes, "%" is a str.

I don't think you should loop. If you are using pySerial, there is a read_until() command that should work well for you.
inp_data = ser.read_until(b"%")
This will wait forever unless you set a timeout on the port.
ser = serial.Serial(port, baudrate, timeout=1.0, ...)   # Timeout read if wait > 1 second
From your post it looks like you already set a timeout.


RE: Waiting for input from serial port, then move on - KenHorse - Oct-17-2023

Thanks, that did the trick


RE: Waiting for input from serial port, then move on - DeaD_EyE - Apr-17-2024

(Apr-17-2024, 06:45 AM)feistycavities Wrote: The issue with your while loop not closing is because you have an embedded for loop in your code.

The cause was the condition of while. In the code there was the check of equality of
Output:
b"%" == "%"
which never is True. So the loop never break and instead sys.exit() was executed at the end.

Data over Sockets, Serial ports and Pipes are always bytes. Python 2 did not this differentiation, which was a huge problem.