Subsection 5.2.2 Discussion: The Receive Buffer
Now we’ll look at what actually happens while
delay_ms() is running. The USART hardware keeps receiving independently of the CPU and does not pause during delay_ms(). When a byte arrives, the shift register assembles the bits and transfers the byte into the receive data register, RDR, setting the RXNE flag. That byte then remains in RDR until the next time the loop checks RXNE, up to 500 ms later, so one keypress is effectively buffered for free.
A second key pressed while RDR is still full is a different story. The shift register receives it correctly, but when it tries to transfer to RDR, which is occupied, the hardware sets the Overrun Error (ORE) flag and the new byte is silently discarded. The first key survives; any key after it is lost. The program has no way of knowing anything was dropped.
Losing the second key is a deliberate trade-off rather than a bug, and it works fine for a counter that a person drives by hand. The general fix is a UART receive interrupt: every incoming byte immediately triggers an ISR that stores it in a software queue, which decouples reception speed from the main loop’s pace. We’ll come back to that pattern later in the course.
