Lesson 4
18 min
setup(), loop(), blinking an LED and printing to the Serial Monitor at 115200 baud.
Definition
A program (or sketch in Arduino terminology) is a sequence of instructions written in a programming language, which is then translated into machine code for the board. On the ESP32 using the Arduino IDE, a program is organized around two functions:setup(), executed once at startup, andloop(), repeated indefinitely.
An ESP32 program written with the Arduino IDE has the same structure as an Arduino program: two required functions.
setup(): runs only once at startup.loop(): runs repeatedly without stopping.
Here is the shortest possible program: it does nothing, but it is valid. Every program you write afterward will start from this basic structure.
void setup() {
// Configuration goes here, executed only once
}
void loop() {
// Main program logic goes here, repeated indefinitely
}The language is strict about punctuation: a single syntax error can prevent compilation. Here are the basic rules.
delay(500);.{and}define the contents of a function. Every opening brace must have a matching closing brace.digitalWriteworks, whileDigitalWritecauses an error.//and are ignored by the board. They help explain your code.The "Hello World" of electronics is making an LED blink. If your board has a built-in LED connected to GPIO2, you do not need to connect anything. Otherwise, connect an external LED:

const int ledPin = 2;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(500);
digitalWrite(ledPin, LOW); // Turn the LED off
delay(500);
}The three functions used are identical to those in Arduino:pinMode()configures the pin,digitalWrite()turns it on or off, anddelay()pauses the program (in milliseconds).
const int ledPin = 2;: gives the pin a name, making the code easier to read and modify.pinMode(ledPin, OUTPUT);: insidesetup(), declares that the pin controls a component (output).digitalWrite(ledPin, HIGH);: the pin switches to 3.3 V, turning the LED on.delay(500);: the board waits for half a second.digitalWrite(ledPin, LOW);: the pin switches to 0 V, turning the LED off.
The Serial Monitor is your best debugging tool: your program can display messages explaining what it is doing. Remember to set the baud rate to 115200.
const int ledPin = 2;
int counter = 0;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
Serial.println("Program started");
}
void loop() {
digitalWrite(ledPin, HIGH);
Serial.println("LED ON");
delay(500);
digitalWrite(ledPin, LOW);
Serial.println("LED OFF");
delay(500);
counter++;
Serial.print("Number of cycles: ");
Serial.println(counter);
}Notice that the message "Program started" appears only once because it is insidesetup(), while the other messages repeat during every iteration ofloop(). The variablecounteris declared outside the functions. It is therefore global and keeps its value between iterations.
The ESP32 uses Arduino's C++ programming language: every variable has a type. Since the ESP32 has plenty of memory, you have more flexibility than with an Arduino Uno.
trueorfalse).Arduino control structures work exactly the same way on the ESP32. This program makes the LED blink three times quickly, pauses for one second, and displays a different message depending on whether the number of completed sequences is even or odd.
const int ledPin = 2;
int sequence = 0;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int i = 0; i < 3; i++) {
digitalWrite(ledPin, HIGH);
delay(150);
digitalWrite(ledPin, LOW);
delay(150);
}
sequence++;
if (sequence % 2 == 0) {
Serial.println("Even sequence");
} else {
Serial.println("Odd sequence");
}
delay(1000);
}forloop repeats the block that turns the LED on and off exactly three times.%operator returns the remainder of a division:sequence % 2 == 0is true when the number is even.elseblock runs when theifcondition is false.When the same block of code is repeated, you can place it inside a function and call it as many times as needed. This makes the program shorter and easier to read. Here, theflash()function receives the blink duration as a parameter.
const int ledPin = 2;
// Turn the LED on for a given duration, then turn it off
void flash(int duration) {
digitalWrite(ledPin, HIGH);
delay(duration);
digitalWrite(ledPin, LOW);
}
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
flash(100);
delay(100);
flash(100);
delay(700);
}Keep in mind that the ESP32 can executeloop()thousands of times per second when you do not usedelay(). This is very fast, which is why non-blocking timing techniques are often used (we will explore them later).
Thedelay()function has one drawback: during the pause, the program cannot perform other tasks. Themillis()function returns the number of milliseconds elapsed since startup. By comparing this value with the time of the previous change, we can decide when to act without pausing the program.
const int ledPin = 2;
const unsigned long interval = 500;
unsigned long lastChange = 0;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - lastChange >= interval) {
lastChange = now;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn);
}
// Other tasks can run here while the LED is blinking
}unsigned longtype is a large unsigned integer suitable for storing time values in milliseconds.loop()can run freely and monitor other sensors at the same time.!symbol reverses a Boolean value:!trueevaluates tofalse.Good to Know
If your program crashes, the ESP32 automatically restarts and displays an error message (often "Guru Meditation Error") in the Serial Monitor. This is useful for understanding the problem and does not necessarily mean that the board is damaged.
expected "}"indicates that a closing brace is missing.Serial.begin(115200).setup()(executed once) andloop()(repeated continuously).pinMode(),digitalWrite(), anddelay()are the same as on Arduino.Serial.println()) at 115200 baud helps you understand what your program is doing.millis()allows you to manage timing without blocking the program.Exercise
Exercise: SOS in Morse Code
forloop and theflash()function to avoid repeating code.Go Further
millis()and add a second LED that blinks at a different rate (for example, every 300 ms), completely independently of the first LED, without using anydelay().