Simvik

Interrupt-driven transmit queue

Queue bytes for the UART and send them from the data-register-empty interrupt. A medium embedded C problem (UART), run and graded in the browser.

medium · UART · uart · interrupts · ring-buffer

Writing a string to a UART one byte at a time and waiting for each wastes the CPU. Instead, firmware queues the bytes and lets an interrupt send them: the UART raises "data register empty" whenever it can take another byte.

  • tx_write(q, s) queues as many bytes of the string s as fit, enables the interrupt if anything is waiting, and returns how many bytes it queued.
  • tx_isr(q) is the interrupt handler: it returns the next byte to load into the UART's data register. When nothing is left it disables the interrupt and returns -1; otherwise the empty data register would fire the interrupt forever.

Starter code

size_t tx_write(tx_t *q, const char *s) {
  return 0;
}

int tx_isr(tx_t *q) {
  return -1;
}

Example tests

Send a short string

tx_t q = { 0 };
printf("%u ", (unsigned)tx_write(&q, "hi"));
drain(&q);

Expected output:

2 hi|off

A string longer than the queue

tx_t q = { 0 };
printf("%u ", (unsigned)tx_write(&q, "abcdefghij"));
drain(&q);

Expected output:

8 abcdefgh|off

Learn it first

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

More UART problems