All courses

Arduino C++ · Lesson 30 of 40

Separate logic from hardware

Reliable Embedded C++

Make decisions testable without a board

A function that receives values and returns a decision is easier to test than a function that reads pins, updates global variables, prints, and switches a motor all at once. Keep pin reads at the boundary, calculate in a small function, then apply the output.

Use a struct for values that belong together. Pass a small scalar by value. Pass larger read-only structures by const reference when appropriate. A reference names an existing object; it must not refer to a local object after that function returns. Avoid retaining pointers to temporary arrays.

This complete sketch demonstrates hysteresis using a potentiometer instead of a real temperature sensor. The conversion is a simulation and is not a temperature calibration.

Arduino C++
bool alarmFor(float value, bool wasOn) {
  if (value >= 30.0f) return true;
  if (value <= 28.0f) return false;
  return wasOn;
}

bool alarmOn = false;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  const float simulatedC = analogRead(A0) * (40.0f / 1023.0f);
  alarmOn = alarmFor(simulatedC, alarmOn);
  digitalWrite(LED_BUILTIN, alarmOn);
}

Wire a 10 kilohm potentiometer's outer terminals to 5V and GND, and its wiper to A0 on an Uno R3. The LED turns on at a simulated 30 and off at 28, rather than chattering near a single threshold.

Test the decision function: 31/false → true; 29/true → true; 29/false → false; 27/true → false. No physical sensor is needed for these four logical cases.

Grow beyond one large sketch

When the decision logic grows, put declarations in Alarm.h with an include guard or pragma once and definitions in Alarm.cpp. Include Arduino.h in .cpp files that use Arduino APIs. Keep a clear begin() function for pin setup after the core is initialized; avoid performing I/O in global constructors.

Store pin names and timing constants together. Document units in names such as sampleEveryMs and temperatureC. Prefer one source of truth for each setting. A class is useful when it owns a device's state; it is not required for every helper function.

Exercise: Move alarmFor into a separate source file while preserving the four logical test cases. A linker error about multiple definitions often means a non-inline function was defined in a header included by multiple .cpp files.

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.