Sub topic 1
How a sketch runs: setup() and loop()
Prerequisites
This chapter assumes you can do the following:
- Open the Arduino IDE, verify (compile) a sketch, and upload it to a board.
- Connect an Arduino Uno (or a similar board) over USB.
- Explain what a pin, a voltage, and an LED are. A breadboard with an LED and a resistor is useful for the later examples but not required for this chapter.
You do not need to know C++. The chapter introduces the few language features it uses.
What a sketch is
A sketch is an Arduino program. It is a text file with the extension .ino, written in C++ with a set of helper functions that the Arduino core library provides, such as pinMode(), digitalWrite() and delay().
A sketch has no main() function that you write yourself. Every C++ program needs one, so the Arduino core supplies it. Your job is to fill in two functions that the core calls for you: setup() and loop().
The sketch below is the smallest one that compiles:
void setup() {
}
void loop() {
}It does nothing, but it uploads and runs. If you delete either function, the build fails. The linker reports an error such as undefined reference to 'setup' or undefined reference to 'loop', because the hidden main() calls both of them.
What happens behind the scenes
On an AVR board such as the Uno, the core's main() looks roughly like this (simplified):
int main(void) {
init(); // set up timers, ADC and other hardware
initVariant(); // board-specific setup, usually empty
setup(); // your code, runs once
for (;;) {
loop(); // your code, runs again and again
if (serialEventRun) serialEventRun();
}
return 0;
}You never write this code, but knowing it explains the behavior of every sketch:
init()runs before your code. It configures the timer that powersmillis()anddelay(), and it prepares the analog-to-digital converter.setup()runs exactly once.loop()is called inside an endlessfor (;;)loop. When it returns, it is called again right away. There is no pause between calls unless you add one.
When setup() runs
The setup() function runs once each time the board starts. That happens in these cases:
- The board gets power.
- You press the reset button.
- You upload a new sketch.
- A serial connection opens on boards that reset when the Serial Monitor connects. The Uno does this. The Leonardo and boards with native USB do not.
The last case surprises many people. If your sketch seems to restart whenever you open the Serial Monitor, this is the reason.
Use setup() for work that must happen once before the main behavior starts:
- Setting pin modes with
pinMode(). - Starting communication, for example
Serial.begin(9600). - Setting initial states, such as turning an output off.
- Initializing sensors or displays.
When loop() runs
The loop() function holds the behavior that repeats. On an Uno with a 16 MHz clock, an empty loop() can run hundreds of thousands of times each second. Nothing slows it down unless your code does.
The microcontroller keeps running loop() until power is removed. A sketch cannot "finish" the way a desktop program does. If you want it to stop doing something, you write code that makes loop() do nothing, for example by checking a flag.
A first complete sketch
This sketch blinks the built-in LED. It stores the pin number in a constant, configures the pin once in setup(), and repeats the blink in loop():
const int ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}Trace one pass through loop():
digitalWrite(ledPin, HIGH)turns the LED on.delay(500)stops the sketch for 500 milliseconds.digitalWrite(ledPin, LOW)turns the LED off.delay(500)waits another 500 milliseconds.loop()returns and the core calls it again.
One full cycle takes about one second, so the LED blinks at roughly 1 Hz. Later chapters cover pinMode() and digitalWrite() in detail. For now, treat them as the commands that configure a pin and set its output level.
Why the split matters
Why not put everything in loop()? In the blink sketch you could call pinMode() at the top of loop(), and it would still work. It would waste time and hide your intent. Configuration is a one-time step, and keeping it in setup() makes the sketch easier to read and faster to run.
The split also matters for variables. A variable declared inside setup() exists only there, so loop() cannot see it. Values that both functions need must be declared outside both functions. Scope gets its own chapter, but the rule below prevents a common compile error.
int counter = 0; // declared outside both functions: visible to both
void setup() {
Serial.begin(9600);
counter = 10; // setup() can change it
}
void loop() {
counter++; // loop() sees the change
Serial.println(counter);
delay(1000);
}This prints 11, 12, 13 and so on, one value per second. If you moved int counter = 0; inside setup(), the line counter++ in loop() would fail with 'counter' was not declared in this scope.
What the IDE does for you
The Arduino IDE processes your .ino file before the C++ compiler sees it. It does these things:
- It adds
#include <Arduino.h>, which declares the Arduino functions and constants. - It generates function prototypes (declarations) for the functions you define, so you can call a function before its definition appears in the file.
- It joins multiple
.inofiles in one sketch folder into a single file, in alphabetical order after the main file.
Because of this, an .ino file is slightly more forgiving than plain C++. If you move code into .cpp files, you lose these conveniences. You then include Arduino.h yourself and write prototypes by hand.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Build error `undefined reference to 'setup'` | `setup()` is missing or misspelled, for example `Setup()` | C++ is case sensitive. Use the exact lowercase names. |
| Build error about `loop` | `loop()` is missing, or has a different return type | Declare both as `void name()`. |
| Variable not declared in `loop()` | The variable was declared inside `setup()` | Move it outside both functions. |
| Pin does nothing as an output | `pinMode()` was never called, or was called for the wrong pin | Call `pinMode(pin, OUTPUT)` in `setup()`. |
| Serial output is garbled or missing | `Serial.begin()` is missing, or its baud rate differs from the Serial Monitor | Call `Serial.begin(9600)` and select 9600 baud in the monitor. |
| Sketch restarts when the Serial Monitor opens | The board auto-resets on a new serial connection | Expect this on an Uno. Start important work after `setup()` completes. |
| Code after a `while (true)` never runs | An endless loop inside `setup()` or `loop()` blocks the hidden `main()` | Avoid unbounded loops there, or make sure they have an exit condition. |
Edge cases and details
- Return types. Both functions are declared
void, meaning they return no value, and take no parameters. Returning a value fromloop()is not possible. - Execution order is fixed.
setup()always finishes before the first call toloop(). Ifsetup()takes a long time, for example while waiting for a sensor, nothing inloop()runs during that time. - Initial values of variables. Global variables are set to zero before
setup()runs, if you give no initial value. Local variables are not. They hold whatever was in memory, so always initialize them. - Blocking. A call such as
delay(500)pausesloop(). While paused, the sketch cannot read a button or update a second LED. This is acceptable for a first blink sketch. The final chapter of this tutorial replacesdelay()withmillis()so thatloop()keeps running. - Watchdog and resets. The Uno does not reset itself if
loop()runs for a long time. If your sketch hangs, you must press reset yourself, or enable the watchdog timer, which is outside the scope of this chapter. - One program per board. Uploading a new sketch erases the previous one. The board holds one program at a time in flash memory, and it keeps that program when power is off.
Putting it together: a runnable check
This sketch lets you see the difference between setup() and loop() on your own board. It prints one message from setup() and a numbered message from each pass of loop():
unsigned int passes = 0;
void setup() {
Serial.begin(9600);
Serial.println("setup() ran once");
}
void loop() {
passes++;
Serial.print("loop() pass ");
Serial.println(passes);
delay(1000);
}Upload it, open the Serial Monitor at 9600 baud, and watch the output. You see setup() ran once a single time, followed by loop() pass 1, loop() pass 2 and so on. Press the reset button. The count starts again at 1, because passes is initialized to zero each time the board starts.
Exercise
A sketch declares int total = 0; inside loop() and then runs total++; followed by Serial.println(total);. What does it print on each pass, and why? How would you change the sketch so the printed value grows by one each pass?
Show answer
It prints 1 on every pass. The local variable total is created and set to 0 each time loop() is called, so the increment always produces 1. To make it grow, declare int total = 0; outside both functions (a global), or declare it as static int total = 0; inside loop(). Either way the initialization happens only once.
Exercise
You upload a sketch where Serial.begin(9600); is called inside loop() instead of setup(). It still prints, so what is wrong with this approach, and where should the call go?
Show answer
Calling Serial.begin() on every pass reinitializes the serial port again and again, which wastes time and can cause lost or garbled output. It belongs in setup(), because it is a one-time configuration step that should run once before loop() starts.
Exercise
Your Uno sketch prints "setup() ran once" again each time you open the Serial Monitor. Is the sketch broken?
Show answer
No. The Uno resets when a serial connection opens, so setup() runs again from the start. This is normal for the Uno. Boards with native USB, such as the Leonardo, do not reset this way.