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

PlatformIO

Configure, build, upload and inspect firmware

Why embedded software needs a build system

Typing C++ does not specify which processor should execute it. A Mega, an ESP32, and a desktop computer use different target arrangements, startup code, peripheral interfaces, and often different instruction sets. A complete embedded build must select the compiler, target flags, framework, library sources, memory layout, and upload method. A build system coordinates those decisions so a project can be reproduced without manually typing every compiler invocation.

PlatformIO provides that coordination along with package and device tooling. It reads a project configuration, processes selected build environments, obtains required packages, and invokes the relevant tools. Its value is making assumptions explicit. When a build fails, the configuration and log reveal what it selected; the correct response is to inspect the failed stage rather than repeatedly pressing the same button.

VS Code displays and edits the project. The PlatformIO IDE extension exposes project tasks and integrates with editor tooling. PlatformIO Core supplies the command-line implementation behind many tasks. The platform identifies a family of build support and packages; the board identifies target configuration; the framework supplies a programming environment and runtime. None of these is the C++ language itself.

Editor, extension, Core, toolchain and targetConcept diagram
  1. VS Codepresents →
  2. PlatformIO IDEinvokes →
  3. PlatformIO Coreconfigures →
  4. toolchain/frameworktargets →
  5. board

Editor presents tasks through the extension; Core selects configuration and invokes toolchain/framework support for the board.

Neither the editor nor the extension is the C++ language or MCU.

Diagram labels

VS Code · PlatformIO IDE · PlatformIO Core · toolchain/framework · board

The real Mega environment

The inspected arduinoPractice snapshot contains:

ini
[env:megaatmega2560]
platform = atmelavr
board = megaatmega2560
framework = arduino

The section header declares a build environment named megaatmega2560. The name after env: is a project-local label. It happens to match the board identifier here, but an environment called desk-mega could select the same board. Environment name and board identity are different concepts.

platform = atmelavr selects PlatformIO's AVR platform support. That platform supplies the relevant toolchain and build integration through its package definitions. board = megaatmega2560 selects a board manifest with MCU, clock, build, and upload assumptions. framework = arduino selects the Arduino framework supported by that platform/board combination. Choosing Arduino does not choose a particular board by itself.

The official PlatformIO Mega manifest exposes less application flash than the MCU's total physical flash because bootloader reservation is relevant to upload limits. Read build capacity as usable application capacity under the selected configuration, not automatically the chip's total memory. A compatible board can share the ATmega2560 target while differing in USB bridge, regulator, or power routing; the manifest is not a certificate of clone electrical identity.

Reference: PlatformIO Mega board.

Project files and source discovery

platformio.ini is the central project configuration. src/ contains application sources selected for compilation. include/ commonly holds application headers. lib/ holds project-private libraries with their own organization. test/ holds test code used by the test tooling. Some targets use data/ for filesystem images, but that directory does not imply a filesystem exists on every MCU.

.pio/ contains generated environment state such as build outputs and downloaded project-library dependencies. It is normally ignored by Git because it can be regenerated and varies by machine and tool version. Committing it can obscure the actual source/configuration changes and introduce stale binaries. Framework or platform packages can live in PlatformIO's managed package locations beyond the project's .pio/ directory.

Opening only a detached main.cpp loses the visible project root and configuration context. Open the directory containing platformio.ini. A source file in an archive folder such as the practice repository's zOther/ is not automatically part of the normal src/ build. An editor can still parse it, show diagnostics, or offer completion. That does not establish whether the compiler will include it.

Multiple .cpp files under the selected source set are ordinarily separate translation units. Accidentally placing two alternative sketches in src/, each defining setup() and loop(), can produce duplicate definitions at link time. Archive alternatives deliberately, select sources with an explicit filter when appropriate, or organize genuine subsystems behind separate interfaces. File organization affects what the build means.

What happens after Build

Core reads the configuration and resolves the selected environment. Platform/framework/toolchain packages are prepared as needed. Project dependencies are installed according to the environment declaration. The build system determines source files and include paths, and the library dependency machinery decides relevant library compilation according to its rules.

For each C or C++ source unit, preprocessing expands includes and directives; compilation generates object code. Framework and selected library sources may also compile or be reused from valid cached outputs. Linking resolves references and combines the pieces using the target layout. Further conversion produces uploadable firmware formats. The output reports success or identifies a failure stage.

Incremental builds avoid repeating work whose inputs remain valid. A quick second build does not mean the tool ignored your project; it may have reused unchanged objects. Conversely, a changed configuration or dependency can trigger more rebuilding than a one-line application edit. The cache is an optimization, not the canonical definition of the program.

The log's earliest meaningful error matters. A header-not-found error arises before successful compilation of that unit. An undefined-reference error arises after a declaration was available but a matching definition was not linked. A final summary line saying failure gives less diagnostic information than the specific operation above it.

Dependencies and lib_deps

A library supplies reusable declarations and implementations. A header makes declarations available to a translation unit; compiled definitions satisfy references at linking. A dependency declaration tells the project tooling which package should be available. #include <SomeLibrary.h> and lib_deps therefore participate in different stages.

ini
[env:megaatmega2560]
platform = atmelavr
board = megaatmega2560
framework = arduino
lib_deps =
    bblanchon/ArduinoJson @ 7.0.0

This is an illustrative dependency declaration, not a change to the inspected practice project's configuration and not a recommendation that every Mega project needs JSON. The owner/name identifies a package; the version selects a release. A constraint permits a range, while an exact release is more restrictive. Even exact library versions do not pin every platform and toolchain package unless those layers are also controlled.

Saving an arbitrary source file does not make the C++ preprocessor install a library. PlatformIO installs declared dependencies when it processes the environment, including operations that build or otherwise resolve project packages. The IDE may trigger background project reconfiguration after platformio.ini changes, which can cause package processing before a manually requested build. The causal operation is environment/dependency processing, not saving as a language feature.

Installed project library packages ordinarily appear under .pio/libdeps/<environment>/ according to configuration. Inspecting that folder answers which package version was resolved. Editing those downloaded files creates an unrecorded local patch that can disappear on reinstall. If a library needs changes, use a deliberate fork or project-private dependency with provenance.

The dependency finder uses includes and configured analysis behavior; it does not magically infer every possible conditional or dynamic relationship. A library may be present but not compiled as expected, or its header may be selected from an unintended duplicate. Check package identity, include search paths, dependency graph, and conditional flags before adding random global library folders.

References: lib_deps, dependency management.

Build, upload, and monitor are separate

Build produces firmware and can run without a board connected. Upload communicates with a selected device using an appropriate protocol and transfers a built image; the upload task commonly performs required build work first. Monitor opens a communication stream for observing or sending serial data. A successful build says nothing by itself about cable data capability, bootloader communication, or physical wiring.

powershell
pio run -e megaatmega2560
pio run -e megaatmega2560 -t upload
pio device monitor --baud 9600

These commands assume PlatformIO Core is available to that shell and the project directory is current. The IDE's PlatformIO terminal may expose Core even when an unrelated system shell does not. A missing pio command is an executable-discovery problem, not proof that the C++ program is wrong.

upload_port can select a host port for uploading. On Windows it may be a COM port; Linux typically exposes a device path. Auto-detection is convenient but ambiguous when several boards are connected. Ports can change between machines or after bootloader transitions. Avoid committing a personal port setting that breaks every collaborator's environment unless the repository intentionally provides a local override convention.

monitor_speed configures the monitor baud expectation. It does not rewrite Serial.begin in the program. For UART-based communication, mismatched settings can produce unreadable characters. A board can upload successfully while the monitor is wrong. Another program holding the port can prevent either operation from opening it.

Upload failures and physical diagnosis

When no device appears, distinguish power from data. A charge-only USB cable can light the board while exposing no serial device. A board can use a USB-to-UART bridge needing appropriate host support, or native USB with different enumeration behavior. Inspect the actual board and device list rather than assuming every Arduino-style connector behaves identically.

When a port appears but upload fails, verify the selected target, upload protocol, boot mode, and whether the port is busy. A Mega-compatible board normally follows the selected AVR bootloader workflow if its bootloader and connection match that configuration; an ESP32 has different boot-strapping and reset behavior. Repeated upload retries cannot compensate for an incorrect target image.

Disconnect external circuits that interfere with boot or serial pins when diagnosing, using the board's documented guidance. That isolates upload communication from application wiring. An upload log naming one COM port is evidence of the port selected, not conclusive proof it is the intended physical board.

Once upload succeeds, verify execution using a minimal known behavior and the right pin mapping. Compile success, transfer success, and actual behavior are three distinct checkpoints. A complete engineering check follows the program through all three.

Multiple environments and portability

A project can declare several environments, each with target-specific options. Shared [env] settings can reduce repetition; environment-specific values select board, platform, framework, dependencies, or flags. extends and interpolation support reuse, but inherited configuration should remain easy to inspect.

ini
[env]
framework = arduino
monitor_speed = 9600

[env:mega]
platform = atmelavr
board = megaatmega2560

[env:uno]
platform = atmelavr
board = uno

This illustrates two related AVR targets. pio run -e uno selects one; pio run can process configured environments according to project defaults. A build matrix catches differences in types, available memory, and interfaces. It does not prove that pin assignments or wiring are portable.

Adding ESP32 support requires the actual supported platform and board identifier, plus software and electrical adaptation. Moving from 5 V AVR GPIO to 3.3 V GPIO changes interface assumptions. ADC scaling, PWM APIs, timers, concurrency, and memory representation can differ. A shared Arduino framework supplies familiar function names, not identical implementation behavior.

For Raspberry Pi Pico, the inspected official PlatformIO board page documents a supported Pico configuration. Pico 2 W uses different hardware and may require different platform/core support. Do not claim a working environment by changing the board name until the installed platform's manifests and framework support have been verified. A future-proof guide should explain the verification process rather than freeze an untested recipe.

Configuration and source boundaries

build_flags adds compiler/build definitions or options. A definition such as -DAPP_LOGGING=1 can select conditional source behavior. Flags can also alter language versions or diagnostics, but inherited toolchain options may interact with them. Record why a flag exists and check the actual command line when interpretation is unclear.

build_src_filter selects sources within the relevant source directory according to configured patterns. It is useful for deliberate source variants, but hidden exclusions can also explain why a newly written implementation is never linked. A header visible to IntelliSense is not proof the matching .cpp is selected by that filter.

include/ declarations and src/ implementations make subsystem boundaries visible. A future display module can keep public update functions in a header while isolating controller-library includes in its implementation. lib_deps then records the external library; the application interface records how the rest of the program uses it. These layers address different dependency concerns.

File-backed configuration is target-dependent. An ESP32 application may use flash-backed storage or a filesystem supported by its framework. A classic AVR Mega does not obtain a Linux-style filesystem from creating data/. Persistent configuration needs bounded formats, validated contents, write-endurance awareness, and an update/recovery policy appropriate to the selected storage.

Editor diagnostics and real build results

IntelliSense parses source using its view of compiler definitions, include paths, and the language standard. PlatformIO integration supplies environment information to that view. If the editor has stale or incorrect configuration, it can underline a valid include or accept code that the target compiler rejects. An editor diagnostic is useful evidence from a particular tool, not the target build's final verdict.

Choose the intended environment, confirm the root, run a build, and read the actual compiler output. If the build succeeds while squiggles remain, inspect the language service's selected environment and index. If the build fails, repair the underlying source/configuration error rather than dismissing it as an editor problem. A file outside src/ can be diagnostically active while excluded from the build.

A clean build removes generated build outputs for the selected target and reruns required work. pio run -e mega -t clean is useful when stale outputs are a plausible cause. It is not the first remedy for an undeclared name or incorrect resistor wiring. Preserve source and configuration; generated output is the replaceable layer.

Git, reproducibility, and testing

Commit application sources, public headers, project-private library code where appropriate, platformio.ini, relevant tests, and documented setup assumptions. Ignore generated outputs and private machine settings. A collaborator should obtain the project and reconstruct its environment from recorded inputs rather than borrowing a mysterious .pio directory.

Reproducibility is graded rather than absolute. Unpinned package ranges can change; platform packages and compiler versions can affect results; the host installation can contribute differences. Record versions for release verification and use deliberate constraints where stability matters. A build log is useful evidence of what actually resolved.

PlatformIO's CLI supports automated environment builds, and its testing tools can run suitable tests on a host or target depending on configuration. A pure function translating an ADC code into a bar-graph level can be tested without connecting LEDs. The wiring and actual ADC behavior require target checks. Unit tests should verify meaningful behavior rather than merely recite the code's current structure.

A CI build establishes that configured environments compile in the runner's environment. It does not establish upload success, acceptable power demand, button polarity, or motor response. This division lets automation verify the properties it can observe while preserving a concrete physical verification plan.

Reference and diagnostic method

Setting or commandPurpose
[env:name]Name an independent build configuration
platformSelect platform integration and packages
boardSelect target manifest and defaults
frameworkSelect supported runtime/API framework
lib_depsDeclare project library packages
monitor_speedConfigure serial-monitor baud
upload_portSelect upload communication endpoint
build_flagsSupply justified build options/definitions
build_src_filterControl application source selection
pio run -e nameBuild selected environment
pio run -e name -t uploadBuild as needed and transfer firmware
pio device monitorOpen the configured serial monitor

For any failure, identify the environment, the operation, and the earliest specific error. Then ask which input to that operation is wrong: package identity, declaration, definition, source selection, target manifest, port, baud, or physical device state. That method remains useful when a project grows from a five-LED sequence into several files, buses, and networked components.