Simvik

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]
-1

Learn it first

  • UART · Baud rate, framing, errors, flow control and DMA reception.

More UART problems