LESSONEmbedded C · Part 2EP.34 · 20 s

Your first program: main() + while(1)

// WHAT YOU WILL LEARN

Every Embedded C program = #include, int main(void), setup once, then a while(1) loop that never ends.

// LESSON NOTES

Your chip's program has NO END. 🔁

Every Embedded C program has the same 4 parts:
1️⃣ #include <avr/io.h> → the chip's register names
2️⃣ int main(void) → the chip starts here
3️⃣ setup lines → run ONCE (D13 = output, LED ON)
4️⃣ while (1) { } → runs FOREVER

An empty while(1) is just ONE machine instruction that jumps to itself (rjmp .-2). At 16 MHz that's 8 million laps every second.

What if main() returns? There's no operating system to go back to. So avr-gcc adds its own ending: cli (interrupts off) + an endless loop. The chip can't stop.

And Arduino? Same shape. setup() and loop() live inside a hidden main(): setup() once, then for(;;) { loop(); }.

TESTED CODE · ec02_main_while1.c · avr-gcc
// EC L02 - the shape of every Embedded C program
#include <avr/io.h>          // chip's register names

int main(void) {
    // setup: runs ONCE
    DDRB  |= (1 << DDB5);    // D13 = output
    PORTB |= (1 << PORTB5);  // LED ON

    while (1) {
        // loop: runs FOREVER
    }
    // main() never returns - nothing to return to
}

Related lessons