Reputation: 21
I have a microcontroller that sends data via UART at 3 MBaud. The microcontroller sends a start/status Byte every 8000 Bytes. I d'like my python script to read all data and analyse the data between the start bytes.
I know that Python is able to handle 3 MBaud since that code snippet shows the correct positions of start bytes:
ser = serial.Serial('COM3', 3000000, timeout=None)
_RawData = ser.read(100000)
for cnt in range(0, 100000, 1):
#search for start byte and print the position
if(_RawData[cnt] < 128): print(cnt)
But I need to constantly read the data stream, with that example I loose data between the "ser.read(x)" commands. So I need to compare the data while reading the stream:
ser = serial.Serial('COM3', 3000000, timeout=None)
_RawData = []
cnt = 0
for c in ser.read():
cnt += 1
#search for start byte
if(c < 128):
#print start byte position
print(cnt)
# -= start thread =-
_RawData.clear()
_RawData.append(c)
But found out that reading one single byte is too slow for that baudrate, the start byte position is practically randomly generated. Is there a way I can read my data stream, without loss?
Upvotes: 1
Views: 1384
Reputation: 21
I manage to get it to work for me. As suggested in other threads, I implemented the function ser.inWaiting(), which gives the number of bytes waiting in the input buffer (which on my system is limited to 4096 Bytes) and read that amount from uart. Then I looked for the start byte and started a thread to analyse the data:
ser = serial.Serial('COM3', 3000000, timeout=None)
_RawData = []
while True:
#get data in input buffer
bytesToRead = ser.inWaiting()
Buffer = ser.read(bytesToRead)
for cnt in range(0,bytesToRead,1):
#search for start byte
if(Buffer[cnt] < 128):
#print bytes between start bytes
print(len(_RawData))
# -= start thread =-
_RawData.clear()
_RawData.append(Buffer[cnt])
#wait a short time for the buffer to fill
time.sleep(0.001)
That seems to work for now. Thanks for the help.
Upvotes: 1