The best answer is a circular buffer. This is the easiest way to simulate hardware FIFO in pure software.
The real problem is likely to be either how you collect bytes from the UART to put in a buffer, or overflow this buffer.
At 115200 bauds with the usual 1 start bit, 1 stop bit and 8 data bits, you can see as many as 11520 bytes per second. This gives you an average of about 86.8 ฮผs per byte to work with. On a PC, it will look like a lot of time, but in a small microprocessor there may not be so many general instructions or, in some cases, a lot of requests for I / O registration. If you overflow your buffer because bytes arrive on average faster than you can use them, then you will have errors.
Some general recommendations:
- Do not poll I / O.
- Use interrupt Rx Ready.
- Enable FIFO reception, if available.
- Clear FIFO completely in the interrupt handler.
- Make the ring buffer large enough.
- Consider flow control.
The size of your loopback buffer is sufficient to hold the complete message. If your protocol knows the message size limits, you can use higher levels of your protocol to control the flow and survive effortlessly, so that the XON / XOFF flow works correctly in all cases, cross, or RTS / CTS work as expected at both ends of the wire, which can be almost as hairy.
If you cannot make the ring buffer so large, you will need some flow control.
source share