Sub topic 1
How a Sketch Runs: setup() and loop()
Prerequisites
This chapter assumes you can open, verify, and upload a sketch in the Arduino IDE. You need an Arduino Uno connected over USB, with an LED and a resistor on a breadboard. You should know that a pin is a connection on the board, and that voltage is the electrical push that drives current through a circuit.
How a sketch runs
A sketch is an Arduino program. Every sketch has two functions. setup() runs once, after power-up or reset. loop() runs next and then repeats forever.
Controlling a pin
Use pinMode() in setup() to set a pin as an output. Then use digitalWrite() in loop() to switch it HIGH (on) or LOW (off).
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}Variables and data types
A variable is a named place in memory that holds a value. Its data type sets how much memory it uses and what values it can hold.
| Type | Typical use | Size on Uno |
|---|---|---|
| `int` | Whole numbers | 2 bytes |
| `byte` | Small counts from 0 to 255 | 1 byte |
| `bool` | true or false | 1 byte |
| `float` | Decimal numbers | 4 bytes |
| `unsigned long` | Large counts, such as milliseconds | 4 bytes |
Seeing values with the Serial Monitor
Serial.begin() starts communication with your computer. Open the Serial Monitor (the magnifying glass icon in the IDE) to read what the sketch prints.
int blinkCount = 0;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
blinkCount++;
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
Serial.print("Blinks: ");
Serial.println(blinkCount);
}Exercise
Exercise
The sketch above never stops blinking. Why does the LED keep blinking after the last line of loop() runs?
Show answer
After the last line, the board jumps back to the first line of loop() and runs it again. The loop repeats until power is removed or the board resets.