I'm using PySerial
to read from serial port like in the code below.
CheckReadUntil()
read output of the command that I send to serial port until the sequence of symbols readUntil
are in the serial output.
...
self.ser = serial.Serial(comDev, 115200, timeout=10)
...
#Function that continue to read from Serial port until 'readUntil'
#sequence of symbols appears
def CheckReadUntil(self, readUntil):
outputCharacters = []
while 1:
ch = self.ser.read()
outputCharacters += ch
if outputCharacters[-len(readUntil):]==readUntil:
break
outputLines = ''.join(outputCharacters)
return outputLines
However, if there is no sequence readUntil
(for any reason), I'm just stuck in the function CheckReadUntil()
forever. The setting timeout=10
sets up timeout so I'm stuck in a loop that iterates every 10 seconds and does nothing, just waiting.
How it is possible to understand that there was a timeout event so I may exit the infinite loop? Output length may be different.
timeout = None : wait forever / until requested number of bytes are received. timeout = 0 : non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes.
To check that it is installed, start Pyzo and at the command prompt type in: import serial If it just gives you another >>> prompt, all is good. Checking that it is really working.
Totally non-blocking.
PySerial is a library which provides support for serial connections ("RS-232") over a variety of different devices: old-style serial ports, Bluetooth dongles, infra-red ports, and so on.
UPDATE (previous answer was not correct, this is the working code from @konstantin):
...
self.ser = serial.Serial(comDev, 115200, timeout=10)
...
#Function that continue to read from Serial port until 'readUntil'
#sequence of symbols appears
def CheckReadUntil(self, readUntil):
outputCharacters = []
while 1:
ch = self.ser.read()
if len(ch) == 0:
break
outputCharacters += ch
if outputCharacters[-len(readUntil):]==readUntil:
break
outputLines = ''.join(outputCharacters)
return outputLines
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With