All courses

Arduino C++ · Lesson 31 of 40

Read serial commands without unbounded waits

Reliable Embedded C++

Treat incoming bytes as incomplete data

Serial input arrives one byte at a time. A whole command may not be available in one loop. Keep a bounded buffer and act only after a newline. Reject overlong input rather than executing its truncated prefix. This protects a small Uno's SRAM and avoids waiting for a timeout in a blocking readString() call.

The complete sketch below accepts ON and OFF followed by a newline at 9600 baud. Select Newline or Both NL & CR in Serial Monitor.

Arduino C++
#include <string.h>
char command[12];
size_t used = 0;
bool overflowed = false;

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

void loop() {
  if (Serial.available() == 0) return;
  const char c = Serial.read();
  if (c == '\r') return;
  if (c == '\n') {
    command[used] = '\0';
    if (overflowed) Serial.println(F("Command too long"));
    else if (strcmp(command, "ON") == 0) digitalWrite(LED_BUILTIN, HIGH);
    else if (strcmp(command, "OFF") == 0) digitalWrite(LED_BUILTIN, LOW);
    else Serial.println(F("Use ON or OFF"));
    used = 0;
    overflowed = false;
  } else if (!overflowed && used < sizeof(command) - 1) {
    command[used++] = c;
  } else {
    overflowed = true;
  }
}

The reserved final byte stores the terminating zero. A CR byte is ignored; NL ends the command. At most one byte is processed per loop so other tasks can run, although the main loop must still be fast enough to keep up with the input rate.

Try: ON, OFF, an empty line, lowercase on, and a 30-character command. After the long command, send OFF and confirm recovery. For numeric commands use a checked parser such as strtol with an end pointer and range validation; atoi alone cannot distinguish invalid input from zero.

Official references for further study

A useful reminder

Clean Code: Use descriptive constants instead of magic numbers

Instead of calling digitalWrite(13, HIGH) directly in your code, define descriptive constants like const int LED_PIN = 13; at the top of your file. This makes your code self-documenting and extremely easy to update if you change your wiring.