All courses

Arduino C++ · Lesson 36 of 40

Test boundaries and failure behavior

Debugging, Testing, and Portability

A working happy path is only the beginning

Make a table with input, expected result, observed result, and pass/fail. Include boundary values and sequences, not just typical inputs. For a threshold controller, test just below, exactly at, and just above both hysteresis thresholds. For a command parser test empty, valid, malformed, and oversized input.

Separate pure decision functions from Arduino APIs so you can exercise them on a desktop or in a small self-test sketch. Hardware tests are still required for power integrity, wiring, contact bounce, and sensor timing. A simulator passing a sketch does not prove an actual motor circuit is electrically safe.

Make a failing check visible

No external hardware is required. This complete sketch checks the rollover-safe timing expression, prints the number of failed cases, then leaves the onboard LED on only if there is a failure.

Arduino C++
bool due(unsigned long now, unsigned long previous, unsigned long interval) {
  return now - previous >= interval;
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  unsigned int failures = 0;
  if (!due(100UL, 90UL, 10UL)) ++failures;
  if (due(99UL, 90UL, 10UL)) ++failures;
  // Uno R3 uses a 32-bit unsigned long.
  if (!due(4UL, 4294967290UL, 10UL)) ++failures;
  Serial.print(F("Failed cases: "));
  Serial.println(failures);
  digitalWrite(LED_BUILTIN, failures != 0);
}

void loop() {}

Open Serial Monitor at 9600 and press reset to capture the startup result. Expected result is zero failed cases. If adapting to a target with a different unsigned-long width, use a wrap test generated from that target's maximum value rather than assuming 32 bits.

For fault injection, disconnect a sensor only while the circuit is unpowered, restart, and check the missing-device path. A controller should choose a documented safe state instead of reusing an old valid reading forever. Keep diagnostic status separate from measured values.

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.