Fix: lost bytes are never reported
A receive routine checks the data flag before the overrun flag, so overruns disappear. A medium embedded C problem (UART), run and graded in the browser.
medium · UART · find-the-bug · driver · uart · overrun
Bug report. uart_getc(u) must not block: it returns UART_OVERRUN once after bytes were lost (clearing the overrun, which on this UART takes a read of SR followed by a read of DR), otherwise a received byte (0 to 255), otherwise UART_EMPTY. The UART is simulated like an STM32 USART. When the main loop is slow, bytes go missing and the driver never reports an overrun; instead a stale byte comes back. Fix it by changing at most two lines.
Starter code
int uart_getc(uart_t *u) {
uint32_t sr = u->SR;
if (sr & UART_SR_RXNE) return (int)(u->DR & 0xFF);
if (sr & UART_SR_ORE) { (void)u->DR; return UART_OVERRUN; }
return UART_EMPTY;
}Example tests
Too busy to read, so bytes are lost
init();
stall(500);
collect(1, 50);
printf("%d\n",uart_getc(UART1));Expected output:
[-2]
-1Learn it first
- UART · Baud rate, framing, errors, flow control and DMA reception.
More UART problems
- Assemble command lines · Collect received characters into lines, with backspace and overflow handled.
- Parse a modem signal report · Validate a +CSQ reply and convert it to dBm.
- Detect the baud rate · Measure a 'U' character's bit times and snap to the nearest standard baud rate.
- Interrupt-driven transmit queue · Queue bytes for the UART and send them from the data-register-empty interrupt.
- Spot OK and ERROR in a modem stream · Feed received characters one at a time and report complete OK or ERROR lines.
- Driver: a polled UART transmitter · Configure a UART from its register map and send bytes without losing any.
- Driver: receive bytes and detect an overrun · Read the UART's receive register without blocking, and report lost bytes.
- Command console · Split a command line into words, with quoted arguments, and dispatch it through a command table.
- Greenhouse: parse a console command · Parse a technician's command line, and refuse anything malformed or out of range.