Lesson 4 / 1136%

Lesson 4

Your First Program

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.

The Structure of a Program

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.
Diagram: the execution flow of a program (startup, setup() runs once, then loop() repeats continuously).

Here is the shortest possible program: it does nothing, but it is valid. Every program you write afterward will start from this basic structure.

skeleton.ino
void setup() {
  // Configuration goes here, executed only once
}

void loop() {
  // Main program logic goes here, repeated indefinitely
}

Basic Coding Rules You Should Know

The language is strict about punctuation: a single syntax error can prevent compilation. Here are the basic rules.

  • Every statement ends with a semicolon:delay(500);.
  • Curly braces{and}define the contents of a function. Every opening brace must have a matching closing brace.
  • The language is case-sensitive:digitalWriteworks, whileDigitalWritecauses an error.
  • Comments begin with//and are ignored by the board. They help explain your code.

Blinking an LED

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:

  • Connect GPIO2 to a 220-ohm resistor.
  • Connect the resistor to the LED's anode (long leg).
  • Connect the cathode (short leg) to GND.
Wiring diagram: an LED connected to ESP32 GPIO2 through a 220-ohm resistor, with the cathode connected to GND.
blink.ino
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).

Understanding the Program Line by Line

  • 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.
GIF: the ESP32 LED blinking once per second.

Displaying Information in the Serial Monitor

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.

serial_blink.ino
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.

Variables and Data Types

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.

  • int: an integer (32 bits on the ESP32, allowing more than 2 billion possible values).
  • float: a decimal number.
  • bool: true or false (trueorfalse).
  • String: text.
  • const: a value that will never change, such as a pin number.

Using a Condition and a Loop

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.

condition_loop.ino
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);
}
  • Theforloop repeats the block that turns the LED on and off exactly three times.
  • The%operator returns the remainder of a division:sequence % 2 == 0is true when the number is even.
  • Theelseblock runs when theifcondition is false.

Creating Your Own Function

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.

flash_function.ino
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);
}

Every Iteration of loop() Is a Cycle

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).

A Preview: Blinking Without Blocking Using millis()

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.

blink_millis.ino
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
}
  • Theunsigned longtype is a large unsigned integer suitable for storing time values in milliseconds.
  • The board continuously checks whether the interval has elapsed. Therefore,loop()can run freely and monitor other sensors at the same time.
  • The!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.

Common Beginner Mistakes

  • Missing semicolon: the IDE often reports the error on the next line. Check the line immediately above the error message.
  • Missing curly brace: an error message such as expected "}"indicates that a closing brace is missing.
  • Forgetting pinMode: without configuring the pin as an output, the LED may remain off or glow very dimly.
  • Incorrect Serial Monitor speed: if the text is unreadable, make sure the monitor is set to 115200, matchingSerial.begin(115200).
  • LED does not turn on: check the LED's orientation (long leg on the resistor side) and the pin number being used.

Key Takeaways

  • A program is organized aroundsetup()(executed once) andloop()(repeated continuously).
  • The functionspinMode(),digitalWrite(), anddelay()are the same as on Arduino.
  • The Serial Monitor (Serial.println()) at 115200 baud helps you understand what your program is doing.
  • Creating your own functions avoids repeating code, whilemillis()allows you to manage timing without blocking the program.

Exercise

Make the LED blink in a "heartbeat" pattern: two quick 100 ms flashes separated by 100 ms, followed by a 700 ms pause. Display "Heartbeat" in the Serial Monitor during each cycle.

Exercise: SOS in Morse Code

Program the SOS distress signal: three short flashes, three long flashes, then three short flashes, followed by a two-second pause before repeating. Use aforloop and theflash()function to avoid repeating code.

Go Further

Return to the program usingmillis()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().