Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Serial and Communication

Writing a Serial Command Parser

Build a robust Arduino serial command parser: collect bytes into a line buffer without blocking, split command and argument, validate values, and reply with errors.

Reading one character like '1' to switch an LED on is fine for a demo. A real project wants commands: LED 1, SPEED 120, SERVO 45, STATUS. Sending and parsing such commands makes your board scriptable from a PC, a phone app or another microcontroller. The trick is to do it without blocking the rest of your sketch and without crashing on bad input.

The sketches here are real Arduino code and read-only. The C programs are labelled stand-ins that feed the same parsing logic from text, so you can run and extend the parser in the browser.

The plan

  1. In loop(), take whatever bytes have arrived (Serial.available()).
  2. Append each byte to a fixed-size line buffer until you see the newline \n.
  3. When a full line is ready, parse it into a command word and optional number.
  4. Act on it and reply (OK, or ERR with a reason).

Because step 1 handles just the bytes that are present and returns, the sketch stays responsive: blinking, sensor reads and motor updates continue between commands. Compare this to readStringUntil('\n'), which waits (up to the timeout) for the line to finish and freezes everything else.

flowchart LR
  A["Serial bytes arrive"] --> B["Append to buffer"]
  B --> C{"Newline?"}
  C -- no --> A
  C -- yes --> D["Parse command"]
  D --> E["Act and reply"]
  E --> F["Clear buffer"]

The buffer collects pieces; only a complete line triggers parsing.

The Arduino version

C++
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte length = 0;

const int LED_PIN = 9;

void handleLine(char *text) {
  char *command = strtok(text, " ");
  char *argument = strtok(NULL, " ");

  if (command == NULL) {
    return;                                    // empty line
  }
  if (strcmp(command, "LED") == 0 && argument != NULL) {
    digitalWrite(LED_PIN, atoi(argument) ? HIGH : LOW);
    Serial.println(F("OK"));
  } else if (strcmp(command, "BRIGHT") == 0 && argument != NULL) {
    int level = constrain(atoi(argument), 0, 255);
    analogWrite(LED_PIN, level);
    Serial.println(F("OK"));
  } else if (strcmp(command, "STATUS") == 0) {
    Serial.println(F("RUNNING"));
  } else {
    Serial.println(F("ERR unknown command"));
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c == '\r') {
      continue;                                // ignore carriage return
    }
    if (c == '\n') {
      line[length] = '\0';                     // terminate the string
      handleLine(line);
      length = 0;
    } else if (length < MAX_LEN - 1) {
      line[length++] = c;
    }                                          // else: too long, drop extra characters
  }
}

Points that make it robust:

  • Fixed buffer, no String objects. Repeated String concatenation fragments the tiny heap on AVR boards and eventually causes mysterious crashes.
  • Length check before writing, so a long line cannot overflow the buffer (a classic bug that corrupts memory).
  • strtok splits on spaces; atoi converts text to an integer (returns 0 for junk, so validate if 0 is a valid value).
  • constrain clamps a value into a safe range.
  • Replies let the sender know what happened.

Set the Serial Monitor line ending to "Newline" (or "Both NL & CR") so the sketch sees the \n.

Stand-in: the parser in C

The same logic runs below on a text script instead of live serial bytes. The input box simulates what you would type into the monitor, one command per line.

C Stand-in: line buffer and command parser (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Try editing the input: add a very long line (over 31 characters) and see that the buffer limit protects the program, or add a SPEED command to the code.

Binary and framed protocols

Text commands are great for humans. Machines talking to machines often use binary frames such as [0xAA][length][payload...][checksum]: shorter, faster and unambiguous. A start marker lets a receiver resynchronize after a lost byte, a length tells where the frame ends, and a checksum detects damage. The same ideas appear in sensor frames like the one in temperature and humidity sensors.

C Stand-in: build and verify a framed message (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Practical tips

  • Pick one line ending and document it. Be liberal in what you accept (\r, \n, \r\n) and strict in what you send.
  • Make commands case-insensitive if humans type them, and reply with a consistent format (OK ..., ERR ...).
  • Never trust numbers from outside: clamp them, and refuse values that would damage something (a servo beyond its range, a motor direction flip at full speed).
  • Prefer a timeout for partial lines so a half-typed command does not wait forever.
  • For many commands, store them in a table of names and function pointers instead of a long if chain.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a non-blocking line buffer better than readStringUntil('\n') in a busy sketch?

    readStringUntil waits for the line (until a timeout), freezing the sketch. A buffer processes only the bytes that are available and returns immediately.
  2. 2. What must the code check before storing a received byte in a fixed buffer?

    Without a length check, a long line writes past the end of the array and corrupts memory. Keep room for the terminating zero.
  3. 3. What does atoi("abc") return?

    atoi returns 0 when no digits are found, so check the text yourself if 0 is also a legitimate value.
  4. 4. What is a checksum used for in a binary frame?

    The receiver recalculates the checksum; a mismatch means a byte was corrupted and the frame should be dropped.

Summary

  • Collect bytes into a fixed buffer and parse only when a newline arrives, so the sketch never blocks.
  • Split with strtok, convert with atoi, clamp and validate, and always reply.
  • Avoid String in long-running AVR sketches and always bound the buffer.
  • Binary frames add a start marker, length and checksum for reliability.

Next: The I2C Bus