Sub topic 1
What the board does and what a digital pin is
Prerequisites
You need a basic idea of what a program and a variable are. You also need an Arduino-compatible board, a USB cable, and the Arduino IDE installed. This chapter assumes you can read simple C-style code and know the terms voltage, current, and resistance.
What the board does
A microcontroller board is a small computer that runs one program. The board reads inputs, makes decisions, and drives outputs. Its header pins connect the chip to sensors, switches, LEDs, and other parts.
A digital pin is a pin that is either HIGH (about 5 V on a 5 V board) or LOW (0 V). Each pin has a number. Many boards define the name LED_BUILTIN as the pin wired to the onboard LED. A digital pin can act as an input, reading whether a switch is HIGH or LOW, or as an output, setting a device to HIGH or LOW.
Anatomy of a sketch: setup() and loop()
An Arduino program is called a sketch. Every sketch contains two functions:
setup()runs once, after power-up or reset. Use it to configure pins.loop()runs repeatedly aftersetup()finishes.
void setup() {
// Runs once at start-up.
}
void loop() {
// Runs repeatedly, forever.
}Driving a pin with pinMode() and digitalWrite()
pinMode(pin, mode) sets a pin to INPUT or OUTPUT. digitalWrite(pin, value) sets an output pin to HIGH or LOW. Call pinMode() in setup(), and call digitalWrite() in loop().
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // LED on
delay(1000);
digitalWrite(LED_BUILTIN, LOW); // LED off
delay(1000);
}Exercise
If digitalWrite(LED_BUILTIN, HIGH) runs once in setup() and loop() contains no pin writes, what does the LED do?
Show answer
It turns on after start-up and stays on. The pin keeps its last written state until another write changes it.