# Sketch Structure and the Build/Upload Flow — Arduino & Embedded C

Source: https://www.geekswithgeeks.com/en/arduino-embedded-c/sketch-flow

> setup(), loop(), compile, upload, monitor.

## setup() once, loop() forever

An Arduino program is a **sketch**: a `.ino` file inside a folder of the same name. It is C++ with some conveniences: the build adds `#include <Arduino.h>` and generates function prototypes for you. `setup()` runs once after reset (configure pins, start Serial); `loop()` is then called again and again for as long as the board has power. Building **compiles** the sketch plus the core and libraries into a machine-code image, then **uploads** it, typically via the bootloader over USB. After upload the board resets and your code runs; the PC is no longer needed except for the serial monitor.

## Blink: the "hello world" of embedded

Uses LED_BUILTIN, which maps to the on-board LED (pin 13 on the Uno R3; check your board's pinout).

```cpp
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);   // configure the pin as an output
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH); // LED on
  delay(500);                      // wait 500 ms
  digitalWrite(LED_BUILTIN, LOW);  // LED off
  delay(500);
}
```

## Compile, upload and monitor from the terminal

Shown, not run. Replace the port with the one `arduino-cli board list` reports.

```bash
arduino-cli sketch new Blink
# edit Blink/Blink.ino, then:
arduino-cli compile --fqbn arduino:avr:uno Blink
arduino-cli upload  --fqbn arduino:avr:uno -p /dev/ttyACM0 Blink

# open a serial monitor at 9600 baud
arduino-cli monitor -p /dev/ttyACM0 --config baudrate=9600
```

## Upload failing?

Most upload errors come from the wrong board/FQBN, the wrong port, or another program (such as an open serial monitor) holding the port. Check those three first.

**Quiz:** What happens after setup() finishes?

- [ ] The board waits for a command from the PC
- [ ] The program ends and the board turns off
- [ ] setup() is called again
- [x] loop() is called repeatedly for as long as the board is powered

*Answer:* loop() is called repeatedly for as long as the board is powered. There is no OS to return to, so the main loop never exits.
