Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← All Learn guides

LEARN · DEEP GUIDE

C++

From source code to embedded programs

Put the language into practice with complete desktop C++ worked programs, source-linked explanations, and recorded outputs.

What a program actually is

Suppose five LEDs should light from the outside toward the center and back again. That sentence describes behavior, but a processor cannot interpret it. It needs operations expressed in a language that ultimately becomes instructions its circuitry can execute. An algorithm is the procedure: select pins, drive an outer pair, wait, release that pair, and repeat with other pairs. A program expresses that procedure along with the data and rules needed to run it.

Source code is the text you write. It is a representation of a computation, not the computation already happening. Saving a file changes bytes on your computer's storage. Building translates the project into a target program. Uploading transfers that result to a board. Executing occurs when the board's processor runs the instructions. These stages can succeed or fail independently. A program can compile perfectly and control the wrong pin because the program's assumptions do not match the circuit.

A CPU repeatedly fetches instructions, decodes them, and performs operations. Instructions can load data, add values, compare values, branch, and access peripherals. A clock coordinates operations, but one C++ statement does not necessarily equal one instruction or one clock tick. The compiler may expand one expression into many instructions, inline a function, or remove work whose result has no observable effect. Reason about the behavior promised by the language, then measure timing when hardware timing matters.

Memory contains representations of values. A bit has two possible states; an eight-bit byte has 256 possible patterns. The same pattern can mean an unsigned number, part of a character, an instruction, or a portion of a larger value. Type and context determine its meaning. A processor is not seeing the variable name ledPin written on a memory cell. Names help humans and the compiler; the generated program works with addresses, registers, and values.

Firmware is software intended to run within a device and control its behavior. It is often stored in nonvolatile flash so it survives loss of power. Runtime variables usually occupy RAM, whose contents ordinarily disappear when power is removed. The source file on the laptop, firmware in flash, and live variables in RAM are three different things. Uploading a new program can change the first of the board's two stores without turning all runtime state into permanent data.

Source, compile, link, upload, board behaviorConcept diagram
  1. source codecompile →
  2. compilerproduce →
  3. object filesresolve →
  4. linkerlink →
  5. firmware imagetransfer →
  6. upload transportprogram flash →
  7. microcontroller

Compile source into objects, link the image, then upload through a transport to program flash.

Compiler and linker are separate stages; upload is not compilation.

Diagram labels

source code · compiler/linker · firmware image · upload transport · microcontroller

From source to firmware

A toolchain is the collection of programs that turns source into target code. Preprocessing handles directives such as #include. Compilation translates a translation unit into an object file. An object file contains machine code and data plus information about symbols it defines or still needs. The linker combines object files and selected library code, resolves references among them, and lays out the program according to the target's memory arrangement. Later tools can convert the linked result into a firmware image suitable for upload.

This division explains two apparently similar errors. If a compiler says setIndicator was not declared, it lacks a declaration needed to interpret the call. If the linker reports an undefined reference, compilation may have accepted a declaration but the build never supplied the matching definition. Installing another editor does not resolve either problem. The missing information is in the program or build configuration.

Compile time is when translation and related checks happen. Runtime is when the built program executes. The compiler can reject an unknown identifier or mismatched function signature without any board connected. It generally cannot prove that a breadboard wire reaches the pin the program names. Warnings are also evidence: a conversion warning may reveal that a sensor value is being narrowed. A successful build with warnings is not equivalent to a carefully understood program.

A build system coordinates these tools. It determines which source files belong to an environment, which compiler and flags to use, and which framework and libraries to supply. PlatformIO does this for embedded projects. The compiler itself interprets C++ language rules. Keeping those roles separate gives each failure a place to investigate.

Separate unit compilation and final symbol resolutionConcept diagram
  1. translation unit Acompile →
  2. object A
  1. translation unit Bcompile →
  2. object B

object A + object B → linker → firmware

Both translation units compile independently; object references join at the linker.

Headers provide declarations; the linker needs definitions.

Diagram labels

translation unit A · translation unit B · object A · object B · linker · firmware

Snapshot context. The source history described below is from the package’s inspected snapshot. Current club examples use VS Code + PlatformIO and normal .cpp files with explicit framework headers. Use the current Intro Labs for buildable source.

C++ and the Arduino framework

C++ is a programming language. Arduino is an ecosystem that includes boards, frameworks, APIs, and tools. The Arduino framework provides names such as pinMode, digitalWrite, and Serial, plus startup machinery that eventually calls your setup() and repeatedly calls your loop(). Those names are not built into the C++ language. A desktop C++ compiler does not automatically know what digitalWrite means.

The Arduino IDE is one development application. VS Code is another editor that can host extensions. PlatformIO supplies project configuration, package management, and build/upload operations. You can use C++ with an Arduino framework through PlatformIO inside VS Code; each item is serving a different role. Changing the editor does not change the language, and choosing framework = arduino does not turn a Mega into an ESP32.

Arduino sketch processing normally joins .ino files, inserts the Arduino include if needed, and generates some function prototypes. Normal .cpp files are compiled as ordinary C++ translation units. Consequently a PlatformIO Arduino-framework src/main.cpp normally begins with #include <Arduino.h>, and helper functions need declarations before calls that require them. Automatic sketch processing is a convenience with limitations, not a different programming language.

The club's canonical Intro Lab .ino files remain source assets. This guide explains how to read them; it does not migrate them. The inspected arduinoPractice project already uses an explicit Arduino include in a .cpp source and targets megaatmega2560. That distinction is useful when moving from a single sketch to multiple source files.

Source: Arduino sketch build process.

First program structure

Read a function definition as an interface followed by a body:

cpp
void setIndicator(bool on) {
    digitalWrite(LED_BUILTIN, on ? HIGH : LOW);
}

void says the function returns no value. setIndicator names the function. The parentheses introduce its parameter list; bool on creates a named parameter whose value is supplied by the caller. Braces delimit the body. The body contains a call expression used as a statement, terminated by a semicolon. Indentation makes the structure visible to the reader; braces establish it for the compiler.

Calling setIndicator(true) requests execution of that body with on initialized from the argument true. A parameter is part of the function definition; an argument is the expression supplied at a call. The distinction matters when a function accepts values computed elsewhere. setIndicator(sensorReading > threshold) passes the result of a comparison, not the sensor's original number.

An expression computes a value or produces effects. A statement specifies an action in the program's control structure. count + 1 is an expression; count = count + 1; is an expression statement that changes an object. A function definition is not a function call. Merely defining setIndicator does not cause an LED to change.

Comments record explanations for readers. // comments extend to the end of the line; /* ... */ comments span a block of text. They do not implement behavior. A comment saying “wait one second” beside delay(250) cannot override the actual argument. Useful comments describe intent, assumptions, and reasons that code alone does not communicate.

In the canonical first Blink, setup() configures output direction once, then loop() requests HIGH, waits, requests LOW, and waits again. Its two 1000 ms delays make an approximately two-second cycle. The LED remains in its last output state between writes. The program does not have to keep saying HIGH while it waits; the peripheral retains the requested state.

Values and types

A variable is a named object whose value can change when the program permits it. A type determines the values it can represent and the operations that apply. bool expresses a logical state, char represents a character-sized integer type, integer types represent whole-number values, and floating-point types approximate a range of real numbers. A literal is a value written directly in source, such as 42, true, 'A', or 3.3f.

Width matters. An unsigned eight-bit integer can represent 0 through 255. A signed integer also represents negative values and has a different range. Ordinary int is not guaranteed to be 32 bits: AVR Arduino targets commonly use a 16-bit int. Code that works with a 100000-count value on one board may overflow on another. Where the format requires a specific width and that type exists, <stdint.h> types such as uint16_t and uint32_t make the requirement explicit.

cpp
uint16_t sample = 1023;
uint32_t elapsedMs = 100000;
bool pressed = false;
char command = 's';

Unsigned arithmetic wraps modulo one more than its maximum representable value. Signed overflow is undefined behavior; it is not a portable way to wrap a counter. Converting a wide number into a narrow type can discard representable information. Integral promotions also matter: small integer operands can be promoted before an operation. Writing uint32_t result = a * b; does not by itself guarantee that multiplication occurred in 32 bits. Convert an operand before the operation when the range requires it, for example uint32_t(a) * b for appropriately bounded unsigned inputs.

Floating point trades exactness for range. Many decimal fractions cannot be represented exactly in binary. Repeatedly adding an approximation introduces rounding, and comparing computed floating values for exact equality can surprise you. On classic AVR Arduino targets, double commonly has the same representation as float; other targets can differ. A name that sounds more precise is not evidence about a particular toolchain.

Integer division discards the fractional part toward zero. 3 / 2 produces 1. 3.0f / 2.0f produces approximately 1.5. If an ADC conversion formula performs integer division first, assigning the result to a floating variable afterward cannot recover the lost fraction. Choose the arithmetic representation before computing the result.

const prevents modification through a particular declaration. const uint8_t ledPin = 8; tells readers and the compiler that this name is a fixed pin selection. constexpr declares an entity subject to constant-expression requirements and is useful for values that must be available at compile time. Neither means that every associated byte must physically reside in flash. Placement and initialization depend on the target and toolchain.

Prefer initialization at declaration. A local scalar declared without an initializer can lack a usable initial value. Using such a value is not “getting a random number”; it can violate language rules. Similarly, a variable being declared successfully does not establish that its current value lies within a sensor's valid operating range. Type correctness and domain correctness are separate checks.

See this mechanism in complete desktop programsBrowse all worked programs →

Operators and expressions

Assignment = stores a new value; equality == compares values. if (enabled = true) assigns true and then tests the result, which is usually an unintended condition. Comparisons such as <, >=, and != produce Boolean results. Logical &&, ||, and ! combine logical conditions. The built-in && and || operators short-circuit: the second operand is evaluated only when needed to determine the result.

Arithmetic operators include +, -, *, /, and %. Remainder is useful when cycling through indices, provided its operands and zero-divisor cases are understood. count += 1 updates a value using compound assignment. Prefix increment ++count yields the updated value; postfix count++ yields the previous value while also incrementing. In a loop's increment clause that result is often unused, but the distinction matters inside larger expressions.

Precedence describes how an expression groups. Multiplication groups more tightly than addition, so offset + scale * sample means offset + (scale * sample). Grouping is not the same as evaluation order. Avoid expressions whose correctness depends on obscure sequencing of several modifications. Separate steps are easier to verify, especially when I/O has observable effects.

Bitwise operators work on integer bit patterns: & AND, | OR, ^ XOR, ~ complement, and shifts <</>>. Logical AND asks whether conditions are true; bitwise AND selects common set bits. A bit mask chooses particular positions. flags & mask tests whether any selected flag is set; (flags & mask) == mask asks whether all selected bits are set. Parentheses make that intent visible.

cpp
const uint8_t Ready = 0x01;
const uint8_t Fault = 0x02;
uint8_t flags = Ready | Fault;
bool faultPresent = (flags & Fault) != 0;
flags &= static_cast<uint8_t>(~Fault);

The example manipulates an ordinary variable. It is not a recommendation to write arbitrary hardware addresses. Register access has device-specific access rules, side effects, and synchronization requirements. Learn the bit pattern model separately before applying a documented register interface.

See this mechanism in complete desktop programsBrowse all worked programs →

Decisions and repetition

if chooses a branch based on a condition; else if evaluates another condition if earlier ones failed; else handles what remains. A condition should express the physical or program decision clearly. For a pull-up button, digitalRead(buttonPin) == LOW describes a pressed state when the switch connects the input to ground. The Boolean variable pressed can then hide electrical polarity from higher-level behavior.

switch chooses among discrete cases of an integral or enumeration value. A break exits the switch; omitting it can allow execution to continue into the next case. Intentional fallthrough needs to be recognizable. An enum class later provides a more expressive state type than unexplained numbers.

A for loop collects initialization, continuation test, and step. In for (int pin = 8; pin <= 12; ++pin), initialization occurs once, the condition is checked before each iteration, and increment happens after the body. The loop visits five values. Changing <= to < excludes pin 12. In the inspected Mega example, this loop configures the pins; subsequent explicitly written phases drive the outside, inner, and center LEDs. The configuration loop itself does not generate the animation.

A while loop checks its condition before the body. A do while checks afterward, so its body executes at least once. break exits the nearest enclosing loop or switch; continue skips to the next iteration of the nearest loop. return leaves the function, optionally providing a result. Returning from Arduino loop() ordinarily lets the framework call it again; it does not switch off the board.

An unbounded loop can prevent other work in a cooperative program. while (!pressed) may wait forever if the input is wired incorrectly. A deliberately blocking operation should have a reason and, where appropriate, a timeout. “The program has not crashed” does not mean it is responsive.

See this mechanism in complete desktop programsBrowse all worked programs →

Arrays and strings

An array holds a fixed number of elements of one type. Its first element is at index zero. With const uint8_t pins[] = {8, 9, 10, 11, 12};, valid indices are 0 through 4. The index names a position in the array, not the corresponding physical pin number. pins[0] is 8. Confusing those two coordinate systems is a common reason a sequence controls the wrong output.

C++ built-in array access does not generally perform a runtime bounds check. Reading pins[5] does not mean “no pin”; it accesses beyond the array and produces undefined behavior. A loop that says i <= count is therefore different from i < count. Array size and valid index range should be considered together.

cpp
const uint8_t pins[] = {8, 9, 10, 11, 12};
const size_t pinCount = sizeof(pins) / sizeof(pins[0]);
for (size_t i = 0; i < pinCount; ++i) {
    pinMode(pins[i], OUTPUT);
}

The sizeof formula works here because pins is still an array. An ordinary array parameter is adjusted to a pointer; sizeof that parameter measures the pointer, not the original array. A function receiving a buffer needs a length, an array-reference interface, or an appropriate bounded view. Passing only an address loses the size information needed to validate access.

A C string is a sequence of characters terminated by a zero character. char label[] = "LED"; contains four characters including that terminator. A receiving buffer needs space for both content and terminator. A character 'A' differs from the string literal "A". One is a character value; the other denotes a terminated array of characters.

Arduino String and standard std::string are library types with different implementations and availability. They can manage length and storage, but operations may allocate dynamic memory. A tiny RAM budget makes repeated string growth costly and can expose allocation failures or fragmentation. Use fixed buffers when bounded messages and predictable storage are important, and check the return conventions of formatting functions. Do not replace one unfamiliar string representation with another without understanding its ownership and capacity.

See this mechanism in complete desktop programsBrowse all worked programs →

Functions as interfaces

A good function separates a question or operation from the code that uses it. bool isPressed(uint8_t pin) can return a logical interpretation of an input. void updateIndicator(bool requestedOn) can express an output decision. Passing information explicitly makes dependencies visible and allows logic to be tested without re-creating the entire board program.

Pass by value initializes a separate parameter object. Modifying it does not modify the caller's original scalar. A reference parameter, such as void increment(unsigned& count), binds to the caller's object and permits modification through that reference. A const reference permits observation without modification through that interface and can avoid a copy for a larger object. For small integers, pass by value is usually simpler; adding references everywhere is not an automatic optimization.

A reference must be bound when initialized and is not reseated by assignment. Assigning through it changes the referred object. A pointer object, by contrast, can usually be assigned another address and can represent null. These are related tools with different interfaces and validity expectations.

Return values express results. A function that computes a scaled sensor value should return it rather than quietly changing an unrelated global. Return by value can be efficient because implementations can eliminate copies where language rules permit. Returning a pointer or reference requires a further question: will the referred object still exist after the function returns? A reference to a destroyed local cannot serve as a result.

Function overloading allows several functions with the same name and different parameter lists. The compiler selects an applicable overload using argument types and conversion rules. The return type alone does not distinguish otherwise identical overloads. When a call chooses an unexpected overload, inspect the argument types rather than assuming the name has a single meaning.

See this mechanism in complete desktop programsBrowse all worked programs →

Scope, lifetime, and storage

Scope controls where a name can be used. Lifetime controls when the object it denotes exists. Storage duration describes how long storage is available. These are not interchangeable. A local static variable has a name visible only within its block but storage that persists across calls. A pointer's scope says nothing about whether its target remains alive.

Automatic local objects are typically stored in a stack arrangement associated with function calls. Each call may need parameters, saved state, and locals; nested calls use additional space. The C++ language describes automatic storage duration without requiring a particular physical stack implementation. Optimized locals can live in registers or disappear entirely. The stack picture is a useful implementation model, not a promise that every local occupies a distinct RAM slot.

Objects with static storage duration include many globals and function-local statics. They persist for the program's lifetime rather than being recreated each iteration. A global is convenient for device state, but every function that modifies it becomes coupled to that state. Restrict access when a subsystem can own the object and expose a small interface.

Dynamic storage is obtained during execution, often from an allocator managing a heap. new constructs an object in such storage; delete destroys it and releases its allocation. Ownership means responsibility for that release. Allocating repeatedly without releasing leaks memory; releasing an object while someone still uses its address creates a dangling pointer. Neither problem is fixed by making the pointer volatile.

On an AVR board with only a few kilobytes of RAM, buffers, globals, stack use, and heap allocations compete for a small budget. An apparently harmless local array can consume most of the remaining stack. Recursive calls can multiply that demand. Static arrays make capacity visible but still cost memory. Evaluate storage, maximum depth, and allocation behavior as part of program design.

See this mechanism in complete desktop programsBrowse all worked programs →

Pointers and references

An address identifies a location in an implementation's memory model. A pointer value can identify an object, a function, a one-past position for appropriate array operations, or null. Its type determines how the language interprets operations through it. int* does not guarantee that the stored address actually points to a live int; validity is a program responsibility.

cpp
int count = 3;
int* location = &count;
*location = 4;
int& alias = count;
alias = 5;

In an expression, &count obtains the address. In a declaration, int* declares a pointer type. In *location = 4, unary * dereferences the pointer to access the target object. The same punctuation can play different roles according to context. The final assignment through alias changes count, because the reference refers to that object.

nullptr expresses a null pointer value. It does not identify an accessible object, so dereferencing it is invalid. A non-null pointer can still be invalid because its target was destroyed or the address is outside an allowed range. Checking only for null does not prove lifetime or bounds. For a borrowed buffer interface, document the required valid extent and how long the caller must keep it alive.

Pointer arithmetic advances by elements, not arbitrary bytes: adding one to a pointer to an array element advances toward the next element of that type. The valid domain is bounded by the relevant array, including a one-past position that cannot itself be dereferenced. Using pointer arithmetic to roam through unrelated objects is not a portable memory-discovery technique.

The arrow p->member accesses a member through a pointer and is conceptually related to (*p).member. The dot object.member accesses it through an object expression. References generally use the dot form. Understanding the receiver's type makes library examples much easier to read.

See this mechanism in complete desktop programsBrowse all worked programs →

Records, enumerations, and classes

A struct groups related data into one type. A sampled measurement could contain a raw value, timestamp, and validity state. Keeping those together prevents accidental pairing of a new value with an old timestamp. A class also defines a type with data and operations; the principal default difference is that class members are private while struct members are public.

cpp
struct Reading {
    uint16_t raw;
    uint32_t timeMs;
    bool valid;
};
enum class Mode { Idle, Running, Fault };

An object is an instance with its own state and lifetime. A member variable belongs to an object; a non-static member function operates with an object as its receiver. Several indicator objects can use the same implementation while retaining distinct pins and states. This is a stronger organizing idea than copying one global-variable block for each LED.

An enumeration names a finite set of values. Scoped enum class values use names such as Mode::Running, reducing collisions and limiting accidental conversions. A state type with named values communicates allowable states better than int mode = 2. It does not automatically enforce all valid transitions; the update logic must still decide whether Running can move directly to Fault.

Public members form an interface. Private members support implementation details and invariants. If the only valid brightness range is 0 through 255, a setter can check or constrain that range before storing it. Private access is a compile-time organizational boundary; it is not an electrical safety system or a security boundary against malicious firmware.

See this mechanism in complete desktop programsBrowse all worked programs →

Constructors, destructors, and ownership

A constructor initializes an object when its lifetime begins. It should establish a valid state, often using a member initializer list. A destructor runs when an object's lifetime ends and can release a resource. RAII connects resource ownership to object lifetime: acquiring and releasing are organized around a type so every exit path follows the same lifetime rules.

For embedded hardware, initialization has phases. A global object's constructor can run before the framework has completed peripheral setup. It is often better for the constructor to store configuration and for an explicit begin() called from setup() to initialize hardware. That separates valid C++ object state from readiness of external peripherals.

cpp
class Indicator {
public:
    explicit Indicator(uint8_t pin) : pin_(pin) {}
    void begin() { pinMode(pin_, OUTPUT); }
    void set(bool on) { digitalWrite(pin_, on ? HIGH : LOW); }
private:
    uint8_t pin_;
};

This object owns configuration, not a heap allocation. There is no need to add a destructor merely because it is a class. RAII becomes more consequential when an object owns a file, buffer, lock, or another resource needing release. Copying an owning object can be dangerous if both copies later release the same resource. A class's copy and move behavior must match its ownership semantics.

Destructors for ordinary automatic objects run as their scopes end. Firmware that runs forever may never take a normal program-termination path, and sudden power loss does not execute a C++ cleanup sequence. RAII improves orderly program behavior; it does not make electrical power interruption orderly. Persistent configuration needs its own integrity and update strategy.

See this mechanism in complete desktop programsBrowse all worked programs →

Templates, lambdas, and library awareness

A template describes a family of declarations parameterized by types or other compile-time values. std::array<uint8_t, 5> expresses an array-like container with an element type and capacity in its type. When the toolchain and standard library support it, this can preserve size information and provide a consistent interface without requiring dynamic allocation. Templates can also produce multiple code instantiations; generic code is not necessarily free in firmware size.

A lambda defines a callable object at the point where it is useful. Its capture list determines how it obtains surrounding values. Capturing by value stores a copy in the callable; capturing by reference relies on the original object's lifetime. A callback stored for later use must not retain references to locals that will be gone. Compact syntax can hide an ownership problem if the lifetime is not examined.

Move semantics allow an operation to transfer resources from a source object when its type implements that behavior. std::move is a cast enabling move-aware selection; it does not physically relocate an object by itself. After a move, the original object's permitted uses depend on its type's contract. Use the destination normally and avoid assuming that every moved-from object is either unchanged or empty.

Smart pointers express common dynamic ownership policies. std::unique_ptr represents exclusive ownership; std::shared_ptr represents shared ownership with bookkeeping. Their availability and overhead must fit the embedded environment. They do not justify dynamic allocation where fixed storage solves the problem better. On a richer target they can make ownership clearer; on a tiny AVR the capacity and library constraints may favor other representations.

The standard library includes utilities and containers, but the language version, target library, exception support, and memory budget all affect what is practical. std::vector can grow dynamically; std::array has fixed capacity. The question is not whether a feature is “advanced.” It is whether its behavior, dependencies, and resource demands match the system.

See this mechanism in complete desktop programsBrowse all worked programs →

GPIO, ADC, PWM, and Serial

pinMode selects an input or output role through the framework. digitalWrite requests a logic level on an output. digitalRead reports an interpreted logic state on an input. An input is a measurement connection with comparatively high impedance; an output actively drives voltage within its electrical limitations. Neither operation changes the board's supply voltage or creates unlimited available current.

INPUT_PULLUP enables an internal pull-up where the selected core supports it. A button to ground then usually reads HIGH when released and LOW when pressed. Treat that polarity explicitly. The pull-up does not make a pin safe for an incompatible external voltage, and enabling one on a different board does not establish the same resistance value.

analogRead obtains an ADC code. Its range, resolution, reference, channel selection, and calibration depend on the board and framework. The code is not automatically volts. A divider or potentiometer connects the physical input voltage to the measurement; interpretation then converts the code into a useful quantity under explicit assumptions.

analogWrite commonly configures PWM on supported pins. A timer repeatedly switches the output, and the duty fraction changes. The pin remains electrically digital during the pulses. Some targets provide genuine DAC functionality through board-specific APIs or behaviors, so check the target. A useful API name does not prove the underlying mechanism.

Serial offers a stream-like interface for debugging or communication. Serial.begin(9600) selects a baud setting where applicable; the monitor must use compatible settings. Serial.print converts a value into output characters, and println adds a line ending. Printing can consume time and buffer space. On some boards Serial is a hardware UART through a USB bridge; on others it represents USB serial. Do not generalize the host connection to every board.

Time without blocking

delay prevents the calling task or foreground flow from proceeding for a duration; other hardware and framework activity can continue according to the target. This is sufficient for a first Blink but becomes restrictive when an input, display, and sensor must all be serviced promptly. Non-blocking design asks whether work is due, performs a small update, and returns so other work can run.

millis() reports elapsed milliseconds using the core's counter representation. On the classic Arduino model it returns an unsigned long that eventually wraps. Comparing now >= previous + interval can fail near that wrap. Unsigned subtraction gives an elapsed difference modulo the counter range:

cpp
unsigned long lastChange = 0;
bool on = false;
void updateBlink(unsigned long now) {
    if (now - lastChange >= 500UL) {
        lastChange = now;
        on = !on;
        digitalWrite(LED_BUILTIN, on ? HIGH : LOW);
    }
}

This fragment needs output setup and calls from loop(); it is an explanatory pattern, not a replacement for a canonical lab. Its elapsed subtraction remains meaningful when the counter wraps if the code checks often enough that the actual elapsed time does not span an entire counter cycle. Using matching unsigned types preserves the intended arithmetic. A cast inserted after signed arithmetic does not repair the original operation.

Updating lastChange = now schedules relative to the last execution and can accumulate drift. Advancing by the interval maintains a scheduled cadence, but missed periods then require a deliberate policy: catch up, skip, or record lateness. A data logger may need a different choice from a visual blink. micros() offers a finer time unit with its own resolution and wrap period; it does not guarantee arbitrary instruction-level timing accuracy.

State, edges, and debouncing

A state variable records information that must survive between updates. A button level asks whether it is pressed now. An edge asks whether that level changed since the previous observation. A toggle should usually react to one accepted press edge rather than every iteration while the button remains down. Otherwise a fast loop can toggle hundreds of times during one human action.

A mechanical contact can alternate between open and closed briefly during a transition. Debouncing distinguishes transient raw changes from an accepted stable state. One approach records the latest raw level and the time it last changed; after that level remains unchanged for an interval, it becomes the stable level. Only a change in the stable level should generate a press event.

This policy has a tradeoff. A longer interval rejects more brief disturbances but delays response and can miss brief intentional presses. Read the canonical debounced-toggle walkthrough alongside the circuit's pull-up explanation. Software filtering cannot fix an input whose voltage floats unpredictably because its reference path is absent.

A finite-state machine makes allowable modes and transitions explicit. A sequencer might have Outside, Inside, and Center states, with a transition when elapsed time reaches that state's duration. Each update can then service input and output without a long chain of delays. Separating the current state, transition condition, and entry action prevents unintended repeated actions.

Avoid treating every variable as independent when combinations are constrained. Three Booleans can represent eight combinations, including impossible ones if only three modes exist. A named enumeration plus transition logic expresses the permitted model more accurately. State machines organize behavior; they do not remove the need to budget execution time.

See this mechanism in complete desktop programsBrowse all worked programs →

Interrupts, volatile, and atomicity

An interrupt permits hardware or the runtime to divert execution to a handler when an event occurs. The interrupted flow later resumes. An interrupt service routine should perform the small amount of time-sensitive work needed, such as recording a flag or incrementing a bounded counter, while leaving slower processing to the normal update flow. Printing, allocating, or waiting inside a handler can violate timing and library assumptions.

volatile tells the compiler that accesses through a volatile-qualified object require special observable treatment under the implementation's rules. It is often used for hardware register interfaces and simple ISR-shared objects in embedded implementations. It does not make a read-modify-write operation atomic, provide a mutex, or solve C++ inter-thread synchronization. The correct synchronization mechanism depends on whether the interaction involves an ISR, threads, DMA, or multiple cores.

An 8-bit CPU may need several instructions to read a wider counter. If an ISR updates it between those instructions, foreground code can observe a value assembled from different moments. Declaring the counter volatile does not prevent that torn read. A documented critical-section facility can protect a short snapshot, after which calculations use the local copy. Preserve and restore prior interrupt state rather than blindly re-enabling interrupts in code that may be called with them already disabled.

Atomicity concerns an operation appearing indivisible to a relevant observer. Visibility and ordering are related but different concerns. ESP32 tasks and multicore Pico programs need their platform's synchronization facilities and supported memory model. A rule appropriate to a simple AVR ISR is not a universal concurrency recipe.

Headers and translation units

#include causes preprocessing to incorporate the named header's contents into the current translation unit. It does not download a package. A header commonly provides declarations needed to compile calls and types. A .cpp file supplies definitions that the linker later combines with other compiled units. Include guards or #pragma once prevent repeated inclusion of one header within a translation unit; they do not prevent multiple ordinary function definitions across different translation units.

cpp
// include/indicator.h
#pragma once
#include <stdint.h>
void beginIndicator(uint8_t pin);
void setIndicator(bool on);
cpp
// src/indicator.cpp
#include <Arduino.h>
#include "indicator.h"
namespace {
    uint8_t indicatorPin = LED_BUILTIN;
}
void beginIndicator(uint8_t pin) {
    indicatorPin = pin;
    pinMode(indicatorPin, OUTPUT);
}
void setIndicator(bool on) {
    digitalWrite(indicatorPin, on ? HIGH : LOW);
}

The implementation includes its own header so disagreements are caught during compilation. An unnamed namespace limits the implementation name's linkage to this translation unit. A named namespace groups public names, accessed with ::. Namespaces prevent naming collisions; they do not create separate processors or memory spaces.

An ordinary non-inline function definition copied into a header can cause multiple-definition linker errors when several .cpp files include it. Appropriate inline definitions and templates have specific rules that allow header-based definitions, but “put everything in a header” is not the general remedy. Similarly, putting a normal global definition in a header can create conflicting definitions. Declare shared objects with a suitable interface and provide a single definition when required.

This organization supports a future display subsystem: the display interface exposes initialization and update operations, while its implementation contains library dependencies and bus details. The caller should not need to know every controller command. A boundary that hides unstable details reduces the number of files affected when the implementation changes.

See this mechanism in complete desktop programsBrowse all worked programs →

Debugging and code quality

Classify a failure before changing code. A compiler error concerns translating a unit. A linker error concerns combining compiled definitions. An upload failure concerns transferring firmware or communicating with a bootloader. A logic error concerns what the running program does. An electrical failure can produce the same visible symptom as a logic error, so test the boundary between them.

For a dark LED, first establish which firmware was uploaded and whether the program reaches the expected update. A limited Serial message can expose state and timing. Then test output polarity, pin mapping, resistor, LED orientation, and common ground. Changing five unrelated things at once destroys the evidence needed to identify the cause.

Find the earliest useful diagnostic, not just the final “build failed” line. A missing header can cause many later errors; an unmatched brace can make unrelated definitions appear invalid. Reduce the program to a small reproducible case when the cause is unclear. Pure computations can often be checked on a host without uploading, while physical consequences still require a board.

Name values by meaning, keep fixed configuration in named constants, and isolate operations that belong together. A giant loop() mixing wiring assumptions, display formatting, networking retries, and button state becomes difficult to reason about because every detail is visible at once. Functions and classes help when they expose a coherent contract. They hurt when layers merely rename one operation while obscuring timing or memory cost.

Intermediate embedded C++ competence means predicting values, lifetime, control flow, resource use, and observable hardware actions. You do not need every language feature to do that. You do need to ask what each abstraction guarantees and which properties belong to the board, framework, or build configuration instead.

See this mechanism in complete desktop programsBrowse all worked programs →

A cooperative program from the pieces

The file-backed cooperative status example combines the preceding ideas without altering a canonical lab. For a classic Uno/Mega Arduino-framework target, a button connects D2 to ground and uses the internal pull-up; the output is the board-defined onboard LED. The example accepts one debounced press event, alternates between Stopped and Blinking modes, and updates a blink schedule while continuing to poll the input. It should be reviewed against the actual board before use.

Follow one iteration. loop() takes a single millis() snapshot and passes it to each update. pressEvent reads the electrical level. A raw change records the new level and its change time. If the level has not remained unchanged for the debounce interval, the function returns false. If it already equals the accepted state, it also returns false. Only a newly accepted LOW transition returns true. This separates raw sampling, stable state, and a one-iteration event.

The caller owns the mode change. It chooses the next enumeration value and invokes setMode, which resets blink timing and places the LED in a known off state. That is an entry action: it runs once on the transition rather than every iteration in the mode. updateIndicator then checks whether Blinking mode is active and whether 500 ms has elapsed. If so, it toggles the retained output state. If not, it returns immediately. The next iteration can still observe a release or press.

This organization gives every piece one responsibility. pressEvent interprets input, setMode establishes a transition's effects, and updateIndicator services time-dependent output. None needs to know an arbitrary global detail from another future subsystem. The unnamed namespace keeps implementation names local to this translation unit; ordinary setup and loop remain visible to the Arduino runtime. Fixed constants express policy, while retained variables express state that changes.

Several design choices are deliberate. A mode change restarts the blink interval. Scheduling from now skips missed periods and can drift; that is acceptable for this indicator but not necessarily for measurement timing. Startup assumes a released button until a sampled stable state says otherwise, so a button held at startup can become an accepted first press. The polling interval must be short relative to intended presses and the full timer-counter cycle. The program contains no blocking delay, but future calls inserted into its loop can still damage response time. Non-blocking architecture is a contract maintained across subsystems.

To extend this program toward a display or sensor, add another bounded update with explicit inputs and state ownership. If its implementation becomes substantial, place its public declarations in a header and its definitions in a separate .cpp. Do not simply add a second independent setup/loop pair. Decide which layer initializes shared buses, how errors are represented, and which timing obligations each update must meet. Those questions turn a collection of working snippets into a coherent embedded program.

Inspect the complete cooperative example

Illustrative Learn program · SHA-256 f16547cd77cf92ff2455bed69fade4bd23f55154974eb909c5c1fb8eecbd5335

cooperative-status.cpp
// Educational example, not an Intro Lab replacement.
// For a classic Uno/Mega Arduino-framework target:
// connect a pushbutton from D2 to GND; LED_BUILTIN is board-defined.
#include <Arduino.h>

namespace {
constexpr uint8_t buttonPin = 2;
constexpr unsigned long debounceMs = 30UL;
constexpr unsigned long blinkMs = 500UL;

enum class Mode { Stopped, Blinking };
Mode mode = Mode::Stopped;
int lastRaw = HIGH;
int stable = HIGH;
unsigned long rawChangedAt = 0;
unsigned long lastBlink = 0;
bool ledOn = false;

bool pressEvent(unsigned long now) {
    const int raw = digitalRead(buttonPin);
    if (raw != lastRaw) {
        lastRaw = raw;
        rawChangedAt = now;
    }
    if (now - rawChangedAt < debounceMs || raw == stable) {
        return false;
    }
    stable = raw;
    return stable == LOW;
}

void setMode(Mode next, unsigned long now) {
    mode = next;
    lastBlink = now;
    ledOn = false;
    digitalWrite(LED_BUILTIN, LOW);
}

void updateIndicator(unsigned long now) {
    if (mode == Mode::Blinking && now - lastBlink >= blinkMs) {
        lastBlink = now;
        ledOn = !ledOn;
        digitalWrite(LED_BUILTIN, ledOn ? HIGH : LOW);
    }
}
} // namespace

void setup() {
    pinMode(buttonPin, INPUT_PULLUP);
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
    const unsigned long now = millis();
    if (pressEvent(now)) {
        setMode(mode == Mode::Stopped ? Mode::Blinking : Mode::Stopped, now);
    }
    updateIndicator(now);
}

Syntax reference

FormRead it as
const uint8_t pin = 8;Fixed named pin value
if (reading >= threshold) { ... }Conditional execution
for (size_t i = 0; i < count; ++i)Visit bounded indices
bool pressed(uint8_t pin)Function returning a Boolean
T& value / const T& valueMutable / read-only reference interface
T* p, &x, *p, nullptrPointer type, address, dereference, null
obj.member / p->memberMember through object / pointer
Namespace::nameQualified name
#include <Arduino.h>Make framework declarations available
now - previous >= intervalElapsed unsigned-time comparison under stated bounds

Consult the linked glossary for concise definitions. The section metadata connects this guide to the preserved lab code assets and official language/framework references. New illustrative snippets show mechanisms; canonical lab programs remain in their source files.