Simvik

Poll with a timeout

Wait for a status bit, but never forever. A medium embedded C problem (Registers and memory-mapped I/O), run and graded in the browser.

medium · Registers and memory-mapped I/O · polling · timeout

Before writing a byte, a driver waits until the transmit register is empty. A bare while loop hangs the whole system if the peripheral never becomes ready.

Call uart_status() until the UART_TXE bit is set, but at most max_polls times. Return true as soon as the bit is seen, and false if it was not seen within the limit. Do not read the status more often than necessary.

Starter code

bool wait_tx_ready(uint32_t max_polls) {
  // Poll uart_status() up to max_polls times; stop as soon as UART_TXE is set.
  return false;
}

Example tests

Ready on the fourth read

mock_ready_after = 3;
bool ok = wait_tx_ready(10);
printf("%d %u\n", ok, mock_polls);

Expected output:

1 4

Never ready

mock_ready_after = 100;
bool ok = wait_tx_ready(10);
printf("%d %u\n", ok, mock_polls);

Expected output:

0 10

Learn it first

  • Registers, volatile and const · How C talks to hardware: memory-mapped registers, what volatile and const promise, register structs and read-modify-write.

More Registers and memory-mapped I/O problems