Understanding the Sketch Structure: setup(), loop(), and Beyond

Every Arduino sketch looks like it has no entry point. There is no main(), yet the board boots, configures GPIO pins, and runs your code forever. The Arduino core supplies a hidden main() that calls your setup() once and your loop() endlessly. This guide covers what runs before, between, and around those two functions, and how the structure behaves on AVR, ESP32, and RP2040 boards.

Quick Takeaways

  • setup() runs once after power-up or reset. Use it for pinMode(), Serial.begin(), and peripheral initialization.
  • loop() runs repeatedly, with no exit. Keep it non-blocking by replacing delay() with millis() timing.
  • Code outside both functions (includes, globals, custom functions, ISRs) runs at compile time or on demand, not in sequence.
  • Both functions must be declared void with no parameters, or the sketch will not link.
Section Runs Typical Content Common Mistake
Global scope Before setup() #include, #define, variables, objects Running statements here (only declarations are allowed)
setup() Once pinMode(), Serial.begin(9600), Wire.begin() Waiting forever for a peripheral
loop() Forever Sensor reads, state logic, output updates Long delay() calls
Custom functions When called Reusable logic, helpers Missing return type
ISR On hardware interrupt Flag-setting, counters Using Serial or delay() inside

The Hidden main(): What Actually Runs

The Arduino core wraps your sketch in a main() function. On AVR boards such as the Arduino Uno (ATmega328P, 16MHz, 2KB SRAM, 32KB flash), the logic is equivalent to this:

// Simplified version of the Arduino AVR core main.cpp
int main(void)
{
    init();          // Configures Timer0 (millis/micros), ADC prescaler, and other peripherals
    initVariant();   // Board-specific hook, usually empty

    setup();         // Your one-time initialization

    for (;;) {       // Infinite loop: no exit condition
        loop();      // Your repeating code
        if (serialEventRun) serialEventRun();  // Dispatches serialEvent() callbacks if defined
    }
    return 0;        // Never reached
}

This explains three behaviors that confuse beginners:

  1. millis() works without setup because init() already started Timer0.
  2. Local variables inside loop() reset on every pass, because each call creates a new stack frame.
  3. Your code never “ends.” The microcontroller keeps cycling until power is removed.

Anatomy of a Complete Sketch

A well-organized sketch follows a fixed top-to-bottom order.

// ---------- 1. Preprocessor directives ----------
#include <Wire.h>              // I2C library
#define LED_PIN 13             // Compile-time constant, uses no RAM
#define BLINK_MS 500UL         // UL suffix prevents 16-bit overflow on AVR

// ---------- 2. Global variables and objects ----------
unsigned long lastToggle = 0;  // Stores last timestamp from millis()
bool ledState = false;         // Tracks current LED state

// ---------- 3. Function prototype (optional in the IDE) ----------
void toggleLed();

// ---------- 4. setup(): runs once ----------
void setup() {
  pinMode(LED_PIN, OUTPUT);    // Configure GPIO as push-pull output
  Serial.begin(115200);        // Start UART at 115200 baud
}

// ---------- 5. loop(): runs forever ----------
void loop() {
  if (millis() - lastToggle >= BLINK_MS) {  // Non-blocking timing check
    lastToggle = millis();
    toggleLed();
  }
}

// ---------- 6. Custom function ----------
void toggleLed() {
  ledState = !ledState;                      // Flip state
  digitalWrite(LED_PIN, ledState);           // Write HIGH or LOW to pin
  Serial.println(ledState ? "ON" : "OFF");   // Report over UART
}

Global Scope: Where Declarations Live

Anything outside a function sits in global scope. Only declarations and definitions are legal here. A statement such as digitalWrite(13, HIGH); at global level will not compile.

Use this area for:

  • Includes like #include <SPI.h>
  • Constants using const uint8_t or #define
  • Global variables that must persist between loop() calls
  • Library objects such as Servo myServo; or LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Prefer const uint8_t over #define for pin numbers. The compiler type-checks it, and it still costs no SRAM, because the value is placed in flash.

Global vs. Static vs. Local Variables

Type Declared Lifetime RAM Use Best For
Global Outside functions Entire runtime Permanent Shared state, counters
Static local static int n; inside a function Entire runtime Permanent Private persistent state
Local Inside a function One call Stack only Temporary math, loop indexes
volatile global Outside functions Entire runtime Permanent Variables shared with an ISR

setup(): One-Time Hardware Initialization

setup() runs once after power-on, a reset, or a sketch upload. Typical tasks:

  • Set pin direction with pinMode(pin, INPUT_PULLUP). This enables the internal pull-up of about 20kΩ-50kΩ on AVR.
  • Start serial with Serial.begin(baud).
  • Initialize buses: Wire.begin() for I2C, SPI.begin() for SPI.
  • Attach interrupts with attachInterrupt(digitalPinToInterrupt(2), isr, FALLING).
  • Configure sensors by writing their control registers.

Set pinMode() before digitalWrite() on the same pin. On AVR, writing HIGH to an input pin enables the pull-up, which can cause unexpected behavior.

Avoid blocking waits in setup(). This line freezes a board with no USB serial monitor attached:

while (!Serial) { }   // Waits for a USB host; safe on Leonardo/ESP32-S2, hangs standalone designs

Add a timeout when the sketch must also run without a computer:

unsigned long start = millis();
while (!Serial && millis() - start < 3000) { }  // Give up after 3 seconds

loop(): The Repeating Engine

loop() is a superloop, the simplest firmware scheduler. Each pass should read inputs, update state, and write outputs, then return quickly.

Why delay() Hurts

delay(1000) halts the CPU in a busy-wait. Button presses, serial bytes, and sensor changes are missed during that second. Use the millis() pattern shown earlier. It returns elapsed milliseconds as an unsigned long, and subtraction handles the roll-over at about 49.7 days correctly.

Method Blocks CPU Accuracy Complexity Use When
delay() Yes ±1ms Lowest Quick tests, single-task demos
millis() No ±1ms Low Multi-task hobby projects
Timer interrupt No µs-level Medium Precise sampling, PWM-like tasks
RTOS task No Scheduler-defined High Complex ESP32 or RP2040 firmware

Custom Functions: Structuring Code Beyond the Two Required Ones

Split repeated logic into functions. The Arduino IDE auto-generates prototypes for .ino files, so you can call a function before its definition. In .cpp files, write prototypes yourself.

// Returns temperature in °C from an analog LM35 sensor (10mV per °C)
float readTempC(uint8_t pin) {
  int raw = analogRead(pin);           // 10-bit ADC value, 0-1023
  float volts = raw * (5.0 / 1023.0);  // Convert counts to volts at 5V reference
  return volts * 100.0;                // LM35 scale: 10mV/°C
}

Guidelines:

  • Give each function one job.
  • Pass values in as arguments instead of editing globals.
  • Use fixed-width types (uint8_t, int16_t) to control memory on 8-bit chips.
  • On the Uno, keep stack depth shallow. Only 2KB of SRAM is shared between globals, heap, and stack.

Interrupt Service Routines (ISRs)

An ISR runs outside the normal loop() flow. It pauses the main code when a hardware event fires.

volatile bool buttonFlag = false;   // volatile: forces the compiler to re-read it from RAM

void onButton() {                   // ISR: no parameters, returns void
  buttonFlag = true;                // Set a flag only; do the heavy work in loop()
}

void setup() {
  pinMode(2, INPUT_PULLUP);                                     // INT0 pin on Uno
  attachInterrupt(digitalPinToInterrupt(2), onButton, FALLING); // Trigger on a falling edge
}

void loop() {
  if (buttonFlag) {
    buttonFlag = false;             // Clear flag before handling
    // Handle the press here
  }
}

Keep ISRs under a few microseconds. Do not call delay(), Serial.print(), or allocate memory inside them.

Multi-File Sketches and Tabs

Large projects split into tabs. Every .ino file in the sketch folder is concatenated into one translation unit, ordered alphabetically after the main file. Shared state needs an explicit declaration to stay readable:

  • Put shared variables in the main .ino file, or in a .h header with extern.
  • Move reusable code into .h and .cpp pairs. These compile separately and need explicit prototypes and include guards.
  • Group constants such as pin maps in a config.h tab.

Platform Differences You Should Know

The setup()/loop() contract is the same everywhere, but the runtime underneath differs.

Feature Arduino Uno (AVR) ESP32 Raspberry Pi Pico (RP2040)
Clock 16MHz Up to 240MHz 133MHz
Cores 1 2 2
Where loop() runs Bare-metal superloop FreeRTOS task (loopTask) Core 0
Extra entry points serialEvent() RTOS tasks via xTaskCreate() setup1() / loop1() for core 1
SRAM 2KB ~320KB-520KB 264KB
Watchdog risk Low High (long loops trigger a reset) Medium

On the ESP32, a loop that never yields can trip the task watchdog. Adding delay(1) or yield() hands time back to the Wi-Fi and system tasks. On the RP2040 with the Earle Philhower core, define setup1() and loop1() to run code on the second core.

Practical Workflow: Non-Blocking Multi-Task Controller

This example blinks an LED, reads a button, and reports status over UART at the same time. None of the three tasks blocks the others.

Wiring (Arduino Uno):

  • LED anode → 220Ω resistor → D13; cathode → GND
  • Push button between D2 and GND (uses the internal pull-up)
  • USB cable for power and serial
const uint8_t LED_PIN = 13;       // Onboard LED
const uint8_t BTN_PIN = 2;        // Button input, active LOW
const unsigned long BLINK_MS = 250UL;   // Blink interval
const unsigned long REPORT_MS = 1000UL; // Serial report interval

unsigned long tBlink = 0, tReport = 0;  // Task timestamps
bool ledOn = false;
uint16_t pressCount = 0;                // Total presses counted
bool lastBtn = HIGH;                    // Previous button reading

void setup() {
  pinMode(LED_PIN, OUTPUT);             // LED as output
  pinMode(BTN_PIN, INPUT_PULLUP);       // Button with internal pull-up
  Serial.begin(115200);                 // 115200 baud UART
}

void loop() {
  unsigned long now = millis();         // Single time snapshot per pass

  // Task 1: blink the LED without delay()
  if (now - tBlink >= BLINK_MS) {
    tBlink = now;
    ledOn = !ledOn;
    digitalWrite(LED_PIN, ledOn);
  }

  // Task 2: detect a button press on the falling edge
  bool btn = digitalRead(BTN_PIN);
  if (lastBtn == HIGH && btn == LOW) {  // HIGH → LOW transition
    pressCount++;
    delay(20);                          // Crude 20ms debounce; fine for a demo
  }
  lastBtn = btn;

  // Task 3: report status once per second
  if (now - tReport >= REPORT_MS) {
    tReport = now;
    Serial.print("Presses: ");
    Serial.println(pressCount);
  }
}

For production designs, replace the delay(20) debounce with a timestamp check, or add a 100nF capacitor across the switch.

Common Sketch Structure Errors and Fixes

Error Message Cause Fix
undefined reference to 'setup' Missing or misspelled setup() Match exact case: void setup()
'loop' was not declared Typo such as Loop() C++ is case-sensitive
expected unqualified-id before 'if' Statement at global scope Move it inside a function
was not declared in this scope Function used before its definition in a .cpp file Add a prototype
Board resets repeatedly Stack overflow or watchdog timeout Shrink buffers, add yield()
Variable resets every pass Declared inside loop() Make it global or static
Garbage serial output Baud mismatch Match Serial.begin() to the monitor

FAQ

Can an Arduino sketch run without a loop() function?

No. The core’s main() calls loop() unconditionally, so the linker fails with undefined reference to 'loop' if it is missing. To run code once, put it in setup() and leave loop() empty: void loop() {}.

How many times does setup() run?

Once per boot. It runs again after a power cycle, a reset-button press, a watchdog reset, or a new upload. On boards with auto-reset such as the Uno, opening the Serial Monitor also triggers a reset.

Can I call setup() from inside loop()?

Yes, because both are ordinary functions. This re-runs initialization but does not reset the hardware or clear global variables. For a true restart, use a watchdog reset or the board’s reset pin.

What happens when loop() reaches its last line?

It returns to the core’s for (;;) loop, which calls loop() again immediately. Execution speed depends on your code. An empty loop on a 16MHz Uno cycles hundreds of thousands of times per second.

Hot this week

Electronics Safety: Mains Voltage, Batteries, and Soldering Hazards

Learn how to stay safe around mains voltage, LiPo batteries, and soldering fumes. Use our bench checklists and build safely today.

Word Clouds and Text Visualization: Useful or Gimmick?

Are word clouds useful or a gimmick? Learn when they work, where they fail, and which Python text visualization methods beat them. Get the code now.

SQL Anti-Patterns: 12 Mistakes That Slow Queries or Break Results

Learn 12 SQL anti-patterns that slow queries or corrupt results, with fixes, code, and benchmarks. Audit your queries today.

Query Optimization: Indexes, Execution Plans, and Faster SQL

Learn SQL query optimization with indexes, EXPLAIN ANALYZE, and rewrite patterns. Copy-ready PostgreSQL code included. Speed up your slow queries today.

How Uber, Lyft, and Airbnb Use Data for Dynamic Pricing

See how Uber, Lyft, and Airbnb turn demand data into dynamic prices, with Python code for surge and booking models. Build your own pricing engine.

Topics

Electronics Safety: Mains Voltage, Batteries, and Soldering Hazards

Learn how to stay safe around mains voltage, LiPo batteries, and soldering fumes. Use our bench checklists and build safely today.

Word Clouds and Text Visualization: Useful or Gimmick?

Are word clouds useful or a gimmick? Learn when they work, where they fail, and which Python text visualization methods beat them. Get the code now.

SQL Anti-Patterns: 12 Mistakes That Slow Queries or Break Results

Learn 12 SQL anti-patterns that slow queries or corrupt results, with fixes, code, and benchmarks. Audit your queries today.

Query Optimization: Indexes, Execution Plans, and Faster SQL

Learn SQL query optimization with indexes, EXPLAIN ANALYZE, and rewrite patterns. Copy-ready PostgreSQL code included. Speed up your slow queries today.

How Uber, Lyft, and Airbnb Use Data for Dynamic Pricing

See how Uber, Lyft, and Airbnb turn demand data into dynamic prices, with Python code for surge and booking models. Build your own pricing engine.

Pivoting and Unpivoting Data in SQL

Learn how to pivot and unpivot data in SQL with PIVOT, UNPIVOT, CASE, and UNNEST. Copy-paste code for SQL Server, PostgreSQL, and Snowflake. Start now.

GDPR for Data Scientists: Your Responsibilities Explained

Learn what GDPR requires from data scientists: lawful basis, minimization, pseudonymization, DSARs, Article 22. Get code and a checklist.

Funnel Analysis in SQL: Find Where Users Drop Off

Learn funnel analysis in SQL with copy-paste queries for ordered steps, drop-off rates, and segments. Build your conversion funnel today.

Related Articles

Popular Categories