I am reading serial data from an esp32 with pySerial. The esp32 is sending the data quite fast (~every 10ms). If I try to read out the data with pyserial, i takes really long.
Without a specified timeout for pySerial class, it takes around 3s to read out my command string and I dont know what it is waiting for. Furthermore, because of the 3s, the buffer is getting bigger and bigger.
With a timeout and with reducing the sending frequency of the esp32 to 200ms, it works. But if i use a too small timeout it won't read out my whole command string I send with the esp32. And i have to adjust the timeout to the sending frequency of the esp.
What irritates me, is that the 'read_until()' method is taking 3s to read until my seperator char. But if the method stops earlier because of the timeout, it already fetched the whole serial data string.
class USBReader:
def __init__(self) -> None:
self.readerThread = Thread(target=self.read_usb)
self.ser = serial.Serial(port='COM3', baudrate=500000, timeout=0.3)
def read_usb(self):
while True:
start = datetime.datetime.now()
self.ser.flushOutput()
try:
start = datetime.datetime.now()
command_ = self.ser.read_until(b';').decode("UTF-8")
end = datetime.datetime.now()
command = command_.replace("\n", "").replace("\r", "")
print(command)
print(end - start)
except UnicodeDecodeError:
print("error")
EDIT:
I found out the problem was with my two Threads i used. One Thread is for reading the data and the second one is for processing it. The processing was done inside a while loop, which was using all the RAM?. I inserted a sleep of 0.01s and everythings works fine