Your first sketch
10 min read
A sketch is the program that runs on your board. It has two parts, and every sketch you write will follow this shape.
setup()runs once when the board starts.loop()runs again and again, for as long as the board has power.
Get ready
- Install the free Arduino IDE on a computer.
- Connect your board with a USB data cable.
- Choose your board and port in the Tools menu.
Blink
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}Press Upload. The small light on the Nano now flashes once a second. Change 500 to 100 and upload again to see it speed up.
See what your board is thinking
The Serial Monitor shows messages from the board. It is the best way to find mistakes.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(analogRead(A0));
delay(200);
}Read a button
Connect a button between D2 and GND. The pin stays HIGH until you press the button.
void setup() {
pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT);
}
void loop() {
bool pressed = digitalRead(2) == LOW;
digitalWrite(13, pressed ? HIGH : LOW);
}If upload fails, check the port, try another USB cable, and check that the cable carries data and not just power. For an ESP32, you may need to hold the BOOT button while it connects.
Quick quiz
1. How many times does setup() run?
2. With INPUT_PULLUP, a pressed button reads…
3. Which tool shows messages from the board?
Score: 0 / 3