2.0 The Two-Part Structure of Every Arduino Sketch
Every Arduino sketch is built around two essential functions: setup() and loop(). Think of it like a board game: setup() is where you prepare the board, place the pieces, and deal the cards. loop() is the actual game, where you take your turn over and over again.
2.1 – Getting Ready
The setup() function is called when your sketch first starts. The code inside its curly braces {} runs only once after the Arduino board is powered on or reset. This is the place for all your one-time preparations.
Key uses for setup() include:
- Initializing variables: Setting the starting values for the information you’ll use later.
- Setting pin modes: Configuring a pin on the Arduino board to be an INPUT or an OUTPUT (for example, setting up a pin to control an LED).
- Starting up libraries: Preparing any specialized code libraries your sketch needs to use.
2.2 – The Main Action
After setup() finishes, the loop() function takes over. As its name suggests, the code inside its curly braces {} runs continuously, over and over again, for as long as the Arduino has power.
This is where you put the main, active code that makes your project do things, respond to sensors, and change over time. The loop() is the core of your program, where the real action happens repeatedly.
2.3 The Basic Sketch Blueprint
Here is the minimal sketch that every Arduino program is built upon. The comments explain the purpose of each part.
// The setup() function runs one time, when the sketch starts.
void setup() {
// Put your setup code here, to run once:
}
// The loop() function runs over and over again, forever.
void loop() {
// Put your main code here, to run repeatedly:
}
Now that you understand the program’s structure, the next step is to learn how to store and manage information within that structure.