Lesson 2 / 8
Module 1Lesson 2⏱ 45 min study

The Anatomy of a Sketch: Memory, Types & The Execution Lifecycle

Master the setup() and loop() lifecycle, examine the three hardware memory spaces (Flash, SRAM, EEPROM), prevent stack/heap collisions, and debug via UART Serial.

✦ Key Architectural Takeaways
  • •Every Arduino sketch requires two fundamental functions: setup() which executes once on reset, and loop() which iterates indefinitely
  • •The ATmega328P has three distinct memory spaces: 32 KB Flash (program code), 2 KB SRAM (variables and stack), and 1 KB EEPROM (persistent configuration)
  • •With only 2,048 bytes of SRAM, dynamic memory allocation (malloc/String) easily causes stack-heap collisions; static buffers and the F() macro in Flash must be prioritized
  • •UART Serial communication transmits ASCII telemetry across TX/RX pins, configured via Serial.begin(baud) and inspected with the Serial Monitor

## The Architecture of an Embedded C++ Program

Unlike desktop programs that launch, execute tasks, and terminate back to the operating system shell, an embedded program never exits. Once power is applied, the microcontroller must run continuously, monitoring sensors and reacting to events until power is physically disconnected.

§

1. The Real Arduino main() Function

The Arduino framework conceals the standard C++ main() function to simplify programming for beginners. Inside the Arduino core runtime, main() is implemented as:

CPPSYSTEM SCHEMATIC
// Native implementation inside Arduino core main.cpp
int main(void) {
    init();          // Initializes hardware timers for millis() and PWM
    initVariant();

    setup();         // Executes user initialization code EXACTLY ONCE

    for (;;) {       // Infinite execution loop
        loop();      // Executes user repetitive code perpetually
        if (serialEventRun) serialEventRun();
    }
    return 0;
}
§

2. The Three Hardware Memory Spaces

Understanding where your code and data reside in hardware is critical to avoiding elusive crashes:

TEXTSYSTEM SCHEMATIC
  +-----------------------------------------------------------------------------+
  | ATmega328P PHYSICAL MEMORY HIERARCHY                                        |
  +------------+----------+-------------+---------------------------------------+
  | Memory     | Capacity | Volatility  | Engineering Function & Contents       |
  +------------+----------+-------------+---------------------------------------+
  | **Flash**  | 32 KB    | Non-Volatile| Stores compiled machine code and      |
  |            |          | (Read-Only) | constant strings. Retained across boot|
  +------------+----------+-------------+---------------------------------------+
  | **SRAM**   | 2 KB     | Volatile    | Runtime memory: global variables,     |
  |            | (2048 B) | (Lost on pwr| function call stack, local variables. |
  +------------+----------+-------------+---------------------------------------+
  | **EEPROM** | 1 KB     | Non-Volatile| Byte-addressable storage for sensor   |
  |            | (1024 B) | (100k writes| calibration, device IDs, and settings.|
  +------------+----------+-------------+---------------------------------------+

Preventing SRAM Starvation with the F() Macro

In standard C++, string literals are copied from Flash ROM into precious SRAM at boot time:

CPPSYSTEM SCHEMATIC
// BAD: Consumes 42 bytes of precious SRAM out of 2048 bytes!
Serial.println("System initialized: Sensor calibration OK.");

// GOOD: The F() macro forces the string to remain in Flash ROM (PROGMEM)
Serial.println(F("System initialized: Sensor calibration OK."));
§

3. Data Types and Bit Widths in 8-Bit AVR

Selecting the appropriate data type conserves memory and accelerates execution on an 8-bit architecture:

TEXTSYSTEM SCHEMATIC
+---------------+------------+------------------------------+---------------------------+
| C++ Data Type | Size (RAM) | Numerical Range              | Recommended Use Case      |
+---------------+------------+------------------------------+---------------------------+
| **boolean**   | 1 byte     | true or false (0 or 1)       | Digital logic flags       |
| **uint8_t**   | 1 byte     | 0 to 255 (unsigned 8-bit)    | Pin numbers, PWM values   |
| **int8_t**    | 1 byte     | -128 to +127 (signed 8-bit)  | Small offsets, counters   |
| **uint16_t**  | 2 bytes    | 0 to 65,535 (unsigned 16-bit)| ADC readings (0-1023)     |
| **int**       | 2 bytes    | -32,768 to +32,767 (signed)  | General math counters     |
| **uint32_t**  | 4 bytes    | 0 to 4,294,967,295 (unsigned)| millis() & micros() timestamps|
| **float**     | 4 bytes    | $pm 3.4 	imes 10^{38}$ (IEEE 754) | Analog sensor math (Slow)|
+---------------+------------+------------------------------+---------------------------+

[!WARNING] Avoid the dynamic String object in Arduino sketches. Because the ATmega328P lacks a memory management unit (MMU), repeated string concatenations cause memory fragmentation in the 2 KB SRAM, leading to sudden device lockups. Always use fixed C-style character arrays (char buffer[32]) instead.

§

4. Interactive Serial Telemetry Implementation

CPPSYSTEM SCHEMATIC
// =============================================================================
// SERIAL TELEMETRY & HARDWARE HEARTBEAT EXAMPLE
// =============================================================================

const uint8_t LED_PIN = 13;
uint32_t lastHeartbeat = 0;
uint16_t loopCounter = 0;

void setup() {
    // Initialize UART Serial at 115200 bits per second
    Serial.begin(115200);
    while (!Serial) {
        ; // Wait for serial port to connect (required for native USB boards)
    }

    pinMode(LED_PIN, OUTPUT);
    Serial.println(F("========================================"));
    Serial.println(F("  ATmega328P Embedded Diagnostic Link   "));
    Serial.println(F("========================================"));
}

void loop() {
    uint32_t currentMillis = millis();

    // Heartbeat every 1000 milliseconds (Non-blocking)
    if (currentMillis - lastHeartbeat >= 1000) {
        lastHeartbeat = currentMillis;
        loopCounter++;

        // Toggle LED state
        digitalWrite(LED_PIN, !digitalRead(LED_PIN));

        // Transmit diagnostic telemetry packet
        Serial.print(F("[TELEM] Timestamp: "));
        Serial.print(currentMillis);
        Serial.print(F(" ms | Heartbeat: "));
        Serial.print(loopCounter);
        Serial.print(F(" | SRAM Free: "));
        Serial.println(freeMemory());
    }
}

// Diagnostic helper to calculate free SRAM bytes between heap and stack
int freeMemory() {
    extern int __heap_start, *__brkval;
    int v;
    return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}