EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 73
Arduino Sketch Structure and Libraries
A tidy program layout.
A sketch has setup(), which runs once, and loop(), which repeats forever. Put pin modes and library start-up in setup, and the repeating logic in loop.
A library bundles ready-made code for a sensor or display. Include it at the top, create an object, and call its functions. Read each library's documentation for its pin and address assumptions.
Avoid long delay() calls; use a millis() timestamp so the loop stays responsive.
EXAMPLE
unsigned long last = 0;
void setup() { pinMode(13, OUTPUT); }
void loop() {
if (millis() - last >= 1000) {
last = millis();
digitalWrite(13, !digitalRead(13));
}
}