Spot OK and ERROR in a modem stream
Feed received characters one at a time and report complete OK or ERROR lines. An easy embedded C problem (UART), run and graded in the browser.
easy · UART · uart · parsing · at-commands
GSM, Wi-Fi and Bluetooth modules answer AT commands with lines ending in \r\n, and finish with a line that is exactly OK or ERROR. Characters arrive one at a time from the UART.
at_feed(a, c) takes the next character. At the end of a line (\n) return 1 if the line was exactly OK, 2 if it was exactly ERROR, otherwise 0; then start a new line. Ignore \r. Return 0 for every other character.
Keep at most 15 characters of a line. A longer line can never be OK or ERROR, but it must not overflow the buffer.
Starter code
int at_feed(at_t *a, char c) {
return 0;
}Example tests
A command echo then OK
at_t a = { 0 };
feed(&a, "AT\r\nOK\r\n");Expected output:
OK |A report, a blank line, then ERROR
at_t a = { 0 };
feed(&a, "+CSQ: 20,0\r\n\r\nERROR\r\n");Expected output:
ERROR |Learn 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.
- 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.