Writing Arduino Code

Anatomy of a Sketch

11 minStudent plan

setup() and loop(), what runs when, and the handful of functions that control every pin on the board.

After this lesson you can

  • Say what setup() and loop() each do
  • Configure a pin and drive it
  • Recognise the syntax errors that catch everyone

Two functions, always

Every Arduino sketch contains exactly two functions, and the board calls both for you.

setup() runs once, the moment the board powers up or resets. It is where you configure things: which pins are outputs, what speed the serial port runs at, initial states.

loop() runs immediately after setup finishes, and then runs again, and again, forever, until power is removed. There is no hidden main() waiting to end the program, when loop() reaches its closing brace it simply starts again from the top.

A sketch with an empty setup() and an empty loop() is valid and does nothing, millions of times a second. Everything you build is filling those two bodies.

In the full lesson

  1. Two functions, always
  2. Talking to a pin
  3. Syntax that will catch you out

This lesson comes with the Student plan. The first module of Programming is free.