Sub topic 2
Anatomy of a sketch: setup() and loop()
This chapter explains the two functions every Arduino sketch must contain, what the board does with them, and the mistakes that most often break a first program. It assumes you can read simple C-style code, that you know a variable holds a value and a function is a named block of code, and that the Arduino IDE is installed with your board connected. The previous chapter covered what the board and its digital pins are. Here the focus is how your program is organized.
A sketch is a program with a fixed shape
A sketch is the Arduino name for a program. It is written in C++ and saved in a file with the .ino extension. Unlike a desktop program, a sketch has no main() function that you write. Instead you supply two functions, and the Arduino core library calls them for you.
Here is the smallest complete blink sketch:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}Both functions have the return type void, which means they return nothing, and both take an empty parameter list. Their names are fixed and case-sensitive. The compiler looks for exactly setup and loop.
The code inside uses pinMode(), digitalWrite() and delay(). They are explained in the next chapters. For now, read them as "make this pin an output", "set this pin high or low" and "wait this many milliseconds".
What setup() does
setup() runs once, at the start of the program. Use it for work that must happen before the main behavior begins:
- Setting pin modes with
pinMode(). - Starting serial communication with
Serial.begin(). - Initializing libraries and sensors.
- Giving variables their starting values when a plain initializer is not enough.
Because it runs only once, code in setup() is not repeated while the board runs. If you put pinMode() in loop(), it still works, but it repeats pointless work on every pass.
What loop() does
loop() runs over and over, as long as the board has power. When the last line of loop() finishes, the core calls it again immediately. The board never "finishes" the sketch. There is no point where the program ends and returns control to an operating system, because there is no operating system.
This has a practical consequence. An empty loop() is not idle. The processor still calls it again and again, many thousands of times per second. Anything you write in loop() therefore runs at that speed unless you slow it down on purpose, which is the job of delay() in the blink sketch.
What the board really runs
The IDE hides one more function. The Arduino core contains its own main(), which looks roughly like this on AVR boards such as the Uno:
int main(void) {
init(); // set up timers, ADC and other hardware used by the core
initVariant(); // board-specific setup, usually empty
setup(); // your code, once
for (;;) {
loop(); // your code, forever
if (serialEventRun) serialEventRun();
}
return 0;
}The exact details differ between board families, but the shape is the same. The core initializes the hardware, calls your setup() once, then calls your loop() inside an endless for (;;) loop. This explains several behaviors that otherwise seem odd:
millis()anddelay()work without any setup from you, becauseinit()has already configured the timer they depend on.- Your
loop()is an ordinary function that returns each time. It is the endlessforloop around it that repeats it. - If you define neither function, linking fails, because the core's
main()refers to both.
Order of execution and the lifetime of variables
Three places can hold a variable, and each has a different lifetime. This is the most useful thing to understand about sketch structure, because it decides whether a value survives from one loop() pass to the next.
| Where declared | Lifetime | Typical use |
|---|---|---|
| Outside any function (global) | Whole run of the program | Pin numbers, state that must persist |
| Inside a function (local) | One call of that function | Temporary results |
| Inside a function with `static` | Whole run, visible only in that function | A private counter or state |
Global variables are created and given their initial values before setup() runs. Local variables are created fresh on each call, so a local variable in loop() starts over on every pass.
The following sketch shows all three. It uses the serial port to print values, so open the Serial Monitor at 9600 baud to see them.
int globalCount = 0;
void setup() {
Serial.begin(9600);
Serial.println("setup() ran");
}
void loop() {
int localCount = 0;
static int staticCount = 0;
localCount++;
staticCount++;
globalCount++;
Serial.print("local=");
Serial.print(localCount);
Serial.print(" static=");
Serial.print(staticCount);
Serial.print(" global=");
Serial.println(globalCount);
delay(1000);
}You will see the message from setup() once. After that, local stays at 1 on every line, while static and global climb by one each second. The static initializer = 0 is applied only the first time the function runs, which is why the count is not reset.
The choice between global and static is mostly about visibility. A global can be read or changed by any function in the sketch. A static is reachable only inside its own function, which limits accidental changes. For something like a blink timer shared between several functions, a global is the normal choice.
Constants for pin numbers
A pin number written as a bare 13 or 8 is easy to mistype and hard to change. Declare it once at the top of the file:
const uint8_t LED_PIN = 8;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}uint8_t is an unsigned 8-bit integer, which holds 0 to 255 and fits any pin number on common boards. The const keyword makes the compiler reject any later attempt to assign to LED_PIN. If you move the LED to another pin, you change one line.
Other things that belong in a sketch file
A sketch can contain more than the two required functions.
- Comments.
// textruns to the end of the line./* text */can span several lines. Comments are ignored by the compiler. - Your own functions. You can define helpers such as
void flash(int times)and call them fromsetup()orloop(). The Arduino build process generates function prototypes for you in.inofiles, so you can usually define a function after the place where you call it. Put helpers in a.cppfile and this convenience goes away, because then you must declare them yourself. - Preprocessor lines.
#include <Servo.h>brings in a library.#definecreates a text substitution. Preferconstover#definefor numbers, becauseconsthas a type and obeys scope rules. - Extra tabs. The IDE can hold several
.inofiles in one sketch folder. They are joined into one program when compiled. Only one of them may definesetup()and oneloop().
The sketch folder must have the same name as the main .ino file. A sketch named Blink lives in a folder named Blink and its main file is Blink.ino. The IDE offers to fix this if you get it wrong.
When setup() runs again
setup() runs once per start of the program, not once per power cycle. Each of these events restarts the program from the beginning:
| Event | Effect |
|---|---|
| Power applied | Program starts, `setup()` runs |
| Reset button pressed | Program restarts, `setup()` runs again |
| New sketch uploaded | New program starts, `setup()` runs |
| Serial Monitor opened (Uno and Nano style boards) | Board auto-resets, `setup()` runs again |
The last row catches many beginners. On boards that use a separate USB-to-serial chip, opening the Serial Monitor toggles a reset line. Your sketch starts over, so any state you built up is lost. Boards with native USB, such as the Leonardo, usually behave differently here, so check your board's documentation before relying on either behavior.
Variables in SRAM do not survive a reset. If a value must persist across resets or power loss, it has to be stored in EEPROM or flash memory, which is outside this chapter.
Common errors and what they mean
Most first-sketch failures come from a handful of causes. The messages below are typical for AVR boards. Exact wording varies by board and IDE version.
| Symptom | Likely cause |
|---|---|
| `undefined reference to 'setup'` or `'loop'` | The function is missing or misspelled, for example `Setup()` or `loop` with a capital letter |
| `expected ';' before '}' token` | A missing semicolon at the end of the previous statement |
| `'led' was not declared in this scope` | The name is misspelled, wrong case, or declared inside a different function |
| `expected '}' at end of input` | Unbalanced braces, so a function was never closed |
| Compiles, but nothing happens | Pin mode never set, or the wrong pin number |
| Behavior changes when the Serial Monitor opens | The board is auto-resetting and `setup()` is running again |
Reading a sketch top to bottom
When you open any sketch, read it in this order:
- Find the globals and constants at the top. They tell you which pins and values it uses.
- Read
setup(). It tells you how the hardware is configured. - Read
loop(). It tells you what happens repeatedly. - Look at any helper functions that
loop()calls.
For the blink sketch, that reading gives: one pin, configured as an output once, then set high, held, set low and held, repeatedly. The whole behavior is visible in about ten lines.
Summary of the model
Your sketch is not the whole program. It is two callbacks that the Arduino core invokes: setup() once after the hardware is initialized, and loop() again and again forever. Globals exist before either runs and last the whole time. Locals live for one call. A reset starts everything over.
This model also hints at a limit. Because loop() is a single sequence of steps, a long wait inside it stops everything else. The blink sketch above uses exactly such waits, and a later chapter shows how to avoid blocking.
Exercise
A sketch declares int count = 0; inside loop(), then does count++; and prints count once per pass. What does it print on the first, second and third pass, and how would you make it print 1, 2, 3?
Show answer
It prints 1 every time, because count is a local variable that is created and set to 0 on every call of loop(). To make it count up, move the declaration outside the function so it is a global (int count = 0; at the top), or declare it inside loop() as static int count = 0;. Both keep the value between passes.
Exercise
You add Serial.println("start"); to setup() of a sketch running on an Uno. Each time you open the Serial Monitor, "start" appears again even though you never pressed reset. Why?
Show answer
Opening the Serial Monitor on an Uno toggles the auto-reset line used for uploading, so the board restarts and runs setup() again. The program has not looped back to setup(). It has started from the beginning.
Exercise
The IDE reports undefined reference to 'loop' after you rename your function to Loop(). Why does the error mention a missing loop when the code has a similar function, and what is the fix?
Show answer
C++ is case-sensitive, so Loop and loop are different names. The core's hidden main() calls loop(), and the linker finds no function by that exact name. Rename Loop() to loop().