Simvik

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 \n and \r\n endings work.
  • '\b' (backspace) removes the last character, if there is one.
  • Empty lines are not delivered.
  • A line of more than LINE_MAX - 1 characters 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