Answer the question
In order to leave comments, you need to log in
How to correctly read data from a serial port?
Good day! Faced the following problem - how to properly organize the reception of data from the com-port. There is a microcontroller that sends packets - a header (3 bytes), the amount of data, the data itself and at the end three zeros. I accept these packages on a PC, the program is in C #. When packets are received, the serialPort dataReceived event is fired, where this data is read. But the problem is that a package sent at a time by MK will not necessarily come in its entirety at once. Most likely, when the event is called, only part of the packet will be in the buffer, the end comes (together with the beginning of the next packet), the next time the event is called. How it is better to organize reading of the data in that case?
Answer the question
In order to leave comments, you need to log in
Here's another "on the fly" option. Put data at the tail of the queue . Do iteration from the head. As soon as you meet the end-of-packet marker (three zeros, not the best marker), pop the data parts. After that, you check this "piece" for length, checksum, etc.
Also, keep in mind that DataReceived will run on a separate thread.
Go option:
в событие: цикл читаем пока читается из порта и пишем в буфер программы
Анализ_буфера()
если, то есть полный пакет :
удалить данные пакета из буфера программы или указатель двинуть на конец пакета в буфере
используем_пакет_по_назначению
иначе, то ничего не делаем ждем события с куском пакета
....
(ждем новое событие)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question