Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

Sketch Anatomy: setup() and loop()

Understand how an Arduino sketch is organized: globals, constants, setup() and loop(), functions, data types, comments and the hidden main() that calls them.

Every Arduino sketch has the same skeleton. Learning it once makes every example in this course readable. This lesson covers what belongs where: global declarations at the top, one-time setup in setup(), repeating work in loop(), and helper functions of your own.

Arduino sketches are C++, with a few conveniences. The IDE adds #include <Arduino.h> for you, generates function prototypes so you can call a function before it is defined, and wraps your code with a main(). Otherwise it is the C++ you know (or the C from our C tutorial).

The skeleton

C++
// 1. Includes and constants
const int buttonPin = 2;
const int ledPin = 13;

// 2. Global variables (state that survives between loop() calls)
int pressCount = 0;

// 3. setup(): runs once
void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

// 4. loop(): runs forever
void loop() {
  if (digitalRead(buttonPin) == LOW) {
    pressCount++;
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

// 5. Your own functions
int doubleIt(int x) {
  return x * 2;
}

Both setup() and loop() must exist, return void and take no arguments, or the linker complains. Even an empty setup() is fine.

What really runs: the hidden main()

The core contains something very close to this:

C++
int main(void) {
  init();           // timers, ADC settings, millis() support
  initVariant();    // board specific
  setup();          // your code, once
  for (;;) {
    loop();         // your code, forever
    if (serialEventRun) serialEventRun();
  }
  return 0;
}

That is why loop() really loops. It also explains something beginners trip over: local variables inside loop() are recreated on every call, while global variables (and static locals) keep their values.

C Stand-in: locals reset, globals and statics persist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The local counter is stuck at 1 because it is reborn each turn. This is the single most common bug in a first state-tracking sketch: someone declares int count = 0; inside loop() and wonders why it never grows.

Data types you will use constantly

Type Size on an Uno Typical use
bool 1 byte on/off flags
byte / uint8_t 1 byte 0 to 255, pin states, raw data
int 2 bytes (โˆ’32768 to 32767) counters, readings
unsigned int 2 bytes (0 to 65535) non-negative values
long 4 bytes bigger signed values
unsigned long 4 bytes time from millis()
float 4 bytes decimals (precision about 7 digits)
char 1 byte characters

On an Uno, int is only 16 bits. On boards with 32-bit processors (Due, ESP32, Nano 33) int is 32 bits. When size matters, use int16_t, uint32_t and friends from <stdint.h>, which mean the same everywhere.

The stand-in below shows the 16-bit wrap-around that surprises people. It uses the fixed-size types so it behaves like the Uno on any computer:

C Stand-in: 16-bit overflow like an Uno int

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

(Signed overflow is formally undefined in C++, and the stand-in forces the conversion explicitly; on the AVR chip the wrap-around is what you observe in practice. Treat it as a bug to avoid, not a feature.)

Comments, constants and style

Use // for a line comment and /* ... */ for a block. Prefer const int ledPin = 13; over #define LED_PIN 13: a const has a type, obeys scope rules and gives better error messages. For values that are never negative or that represent hardware, const byte or constexpr uint8_t is fine.

Good habits, from the first sketch:

  • Name pins and thresholds; avoid magic numbers.
  • Keep loop() short; move steps into functions with clear names.
  • Indent consistently (the IDE's Tools > Auto Format helps).
  • Comment the why (wiring decisions, units) rather than restating the code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How often does setup() run?

    setup() is called once by main() before the infinite loop that calls loop().
  2. 2. Why does int count = 0; declared inside loop() never exceed 1 after count++?

    Locals live only for one call. Use a global or static variable to remember values.
  3. 3. What is the size of int on an Arduino Uno?

    The AVR chip uses 16-bit int, so the range is -32768 to 32767.
  4. 4. Which type is the right choice for the value returned by millis()?

    millis() returns unsigned long, a 32-bit value; storing it in an int truncates it.

Summary

  • A sketch = constants and globals, setup() once, loop() forever, plus your own functions.
  • The core's hidden main() calls init(), setup() and then loop() repeatedly.
  • Locals reset on every call; globals and static locals persist.
  • An Uno int has 16 bits; use uint32_t, unsigned long and friends where size matters.
  • Name your pins and keep loop() short.

Next: Boards Compared: Uno, Nano, Mega and ESP32