Assemble command lines
Collect received characters into lines, with backspace and overflow handled. A medium embedded C problem (UART), run and graded in the browser.
medium · UART · uart · cli · buffer
A serial console sends one character at a time. line_rx is called for each received byte and returns true when l->buf holds a complete line, as a NUL-terminated string without its line ending.
'\n'ends a line.'\r'is ignored, so both\nand\r\nendings work.'\b'(backspace) removes the last character, if there is one.- Empty lines are not delivered.
- A line of more than
LINE_MAX - 1characters does not fit. Drop the whole line: discard everything up to and including its'\n', and deliver nothing for it.
After a delivered line, the next character starts a new line.
Starter code
bool line_rx(line_t *l, char c) {
if (c == '\n') {
l->buf[l->len] = '\0';
l->len = 0;
return true;
}
l->buf[l->len++] = c;
return false;
}Example tests
Two commands with different line endings
line_t l = { 0 };
feed(&l, "led on\r\nled off\n");Expected output:
[led on]
[led off]Backspace
line_t l = { 0 };
feed(&l, "lex\bd on\n");Expected output:
[led on]Learn it first
- UART · Baud rate, framing, errors, flow control and DMA reception.
More UART problems
- 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.
- 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.