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 stringsas 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|offA string longer than the queue
tx_t q = { 0 };
printf("%u ", (unsigned)tx_write(&q, "abcdefghij"));
drain(&q);Expected output:
8 abcdefgh|offLearn 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.
- 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.
- Fix: lost bytes are never reported · A receive routine checks the data flag before the overrun flag, so overruns disappear.
- 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.