Sub topic 8
How a sketch is structured: setup() and loop()
This chapter assumes you have installed the Arduino IDE, can open a new sketch window, and know what a function, a variable, and a statement are in any language. You do not need to have uploaded anything yet. The next chapter opens the Blink example and builds on what you learn here.
What a sketch is
A sketch is the name Arduino uses for a program. It is a text file with the extension .ino, kept inside a folder of the same name. The IDE treats that folder as the project. If you rename the file without renaming the folder, the IDE will complain or offer to fix it.
The language is C++ with a few conveniences added. The IDE hides most of the boilerplate that a normal C++ program needs. In particular, you never write main(). The Arduino core, which is the support code shipped with each board package, already contains one. Your sketch fills in two functions that the core's main() calls for you.
The two required functions
Every sketch must define both of these:
void setup() {
// runs once
}
void loop() {
// runs over and over
}Both return void (nothing) and take no arguments. The names are case sensitive. Setup() or loop without parentheses will not work. If either function is missing, the build fails at the link step with an error such as undefined reference to 'setup' or undefined reference to 'loop'.
What setup() does
setup() runs exactly once. It runs when the board powers on, when you press the reset button, and right after a successful upload. Use it for one-time preparation:
- Setting the mode of pins with
pinMode(). - Starting serial communication with
Serial.begin(). - Initializing sensors, displays, and other libraries.
- Setting starting values for variables.
What loop() does
loop() runs after setup() finishes, and then runs again each time it returns, until power is removed. Your main behavior goes here: read inputs, make decisions, write outputs.
A microcontroller has no operating system to return to, so a program that simply ends has nothing sensible to do. The Arduino design avoids that by repeating loop() forever.
What actually runs: the hidden main()
The core's main() looks roughly like this. This is a simplified version of the AVR core used by the Uno, and other boards differ in details:
int main(void) {
init(); // core setup: timers, ADC, and so on
initVariant(); // board-specific setup
setup(); // your function, once
for (;;) {
loop(); // your function, forever
if (serialEventRun) serialEventRun();
}
return 0;
}This explains several behaviors that surprise newcomers:
- Code in
setup()is not "special". It is an ordinary function that happens to be called once. - Variables declared inside
loop()are recreated on every pass. They do not remember values between iterations unless they arestatic. - Work done by
init()happens before yoursetup(), which is whydelay()andmillis()already work when your code starts.
A complete minimal sketch
This sketch shows both functions together. It configures the built-in LED pin once, then toggles it every half second:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}LED_BUILTIN is a constant the board package defines for the pin attached to the on-board LED. On an Uno it is pin 13. pinMode() is needed only once because a pin keeps its mode until you change it. Putting pinMode() inside loop() would work, but it repeats pointless work.
Where variables go
Where you declare a variable decides how long it lives and who can see it.
const int ledPin = LED_BUILTIN; // global: visible everywhere
int blinkCount = 0; // global: keeps its value
void setup() {
pinMode(ledPin, OUTPUT);
int localInSetup = 5; // local: gone when setup() returns
}
void loop() {
static int passes = 0; // local, but keeps value between calls
int temp = 0; // reset to 0 on every pass
passes++;
blinkCount++;
digitalWrite(ledPin, blinkCount % 2);
delay(500);
}The rules in practice:
| Declaration | Lifetime | Typical use |
|---|---|---|
| Global (outside any function) | Whole run | Pin numbers, state shared by several functions |
| Local inside `setup()` or `loop()` | One call | Temporary calculations |
| `static` local | Whole run, visible only in that function | Counters and state that only one function needs |
| `const` global | Whole run, read only | Pin numbers and fixed settings |
Prefer const int over #define for pin numbers. The compiler checks types for a const, and it takes no more memory in most cases.
Writing your own functions
You can add as many functions as you like. This keeps loop() readable:
const int ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
flash(3, 150);
delay(1000);
}
void flash(int times, int ms) {
for (int i = 0; i < times; i++) {
digitalWrite(ledPin, HIGH);
delay(ms);
digitalWrite(ledPin, LOW);
delay(ms);
}
}Here flash() is defined after it is used. In plain C++ that would be an error, because a function must be declared before a call. The Arduino IDE helps: before compiling, it scans the sketch and generates function prototypes for you. This works for most simple cases. It can fail with unusual signatures, for example a function that takes a custom struct defined later in the file. In that case, add the prototype or move the type definition to the top.
Multiple files in one sketch
A sketch folder can hold several .ino files. The IDE joins them into one file before compiling. The file matching the folder name comes first, and the others follow in alphabetical order. You still define setup() and loop() only once across all of them.
You can also add .h and .cpp files to the folder. Those are compiled as normal C++, so they do not get the automatic prototypes and must include Arduino.h to use Arduino functions:
#include <Arduino.h>Common errors
The mistakes below account for most first-day build failures.
| Symptom | Likely cause | Fix |
|---|---|---|
| `undefined reference to 'setup'` | `setup()` is missing or misspelled | Check the name, the case, and the parentheses |
| `expected ';' before '}' token` | A missing semicolon | Look at the line above the reported line |
| `'x' was not declared in this scope` | A variable used outside the function that declares it | Move the declaration to global scope or pass it as an argument |
| `expected '}' at end of input` | Unbalanced braces | Use Tools > Auto Format to reveal mismatched indentation |
| LED never changes | `pinMode()` missing, or wrong pin | Confirm `pinMode()` is called in `setup()` |
| Counter resets every pass | Local variable in `loop()` | Make it global or `static` |
Edge cases worth knowing
loop()is not a timed interval. It repeats as fast as the processor allows. Aloop()with nodelay()runs thousands of times per second on a 16 MHz Uno.delay()blocks everything else inloop(). For sketches that must do several things at once, you later switch to timing withmillis().setup()runs again after every reset. Values held in ordinary variables are lost, because RAM is cleared or reinitialized at that point.- Opening the Serial Monitor on many boards, including the Uno, resets the board, so
setup()runs again. That is expected behavior, not a fault. - Global variables with initial values are set before
setup()runs. Do not rely on any particular order between globals defined in separate.inofiles.
Checking your understanding
Exercise
A sketch declares int count = 0; as the first line inside loop() and then runs count++;. If it prints count each pass, what does it print, and how do you make it count up?
Show answer
It prints 1 on every pass, because count is recreated and set to 0 at the start of each call to loop(). To make it count up, declare it as a global variable (outside any function) or as static int count = 0; inside loop().
Exercise
You compile a sketch that has setup() but you accidentally typed void Loop() with a capital L. What kind of error do you get, and why?
Show answer
A linker error such as undefined reference to 'loop'. The core's main() calls a function named loop(). C++ is case sensitive, so Loop() is a different function and the call cannot be resolved.
Exercise
Where should Serial.begin(9600); go, and why not in loop()?
Show answer
It goes in setup(). It only needs to run once to configure the serial hardware. Calling it every pass would restart the serial port repeatedly, which wastes time and can garble output.