13.7 ESP32 setup
The Guide
Step 1: Install VS Code and PlatformIO
Run the one-line installer from Installing Python and Setup and tick PlatformIO for ESP32 in its menu, together with VS Code. It installs VS Code and three extensions: PlatformIO IDE, which builds and uploads programs; Serial Monitor by Microsoft, which shows what the board prints and sends what we type (Step 7); and Teleplot, which plots the numbers the board prints (Plot in Teleplot). It also sets the plug button to open Microsoft’s Serial Monitor.
Download VS Code from code.visualstudio.com. Open it, open the Extensions panel, search for PlatformIO IDE and click Install. It builds and uploads programs. Install two more extensions the same way: Serial Monitor by Microsoft, which shows what the board prints and sends what we type (Step 7), and Teleplot, which plots the numbers the board prints (Plot in Teleplot).
The first time VS Code starts with PlatformIO IDE, the extension installs PlatformIO Core, the program that does the actual building and uploading, in the background. This takes a few minutes. Restart VS Code when it asks you to. An alien head icon appears in the left sidebar when the installation is done.
Step 2: Connect the board
Connect the ESP32 board to the computer with a USB-C cable. The cable must carry data. The red LED marked PWR lights as soon as the board has power (Figure 13.7.1).
PWR LED shows that the board has power. BOOT sits left of the USB-C connector and EN to its right. The LED marked D2, below the large chip, is off until a program drives it.
The computer talks to the board through a USB-serial chip next to the connector, a CH340 on the boards in the lab kits and a CP2102 on some other DevKits (From USB to two wires). On Windows the board then appears in Device Manager under Ports (COM & LPT) as USB-SERIAL CH340 (COM5) or similar, and that COM number is the port we choose for the Serial Monitor. If it shows up instead under Other devices with a warning sign, Windows lacks the driver: install it from WCH for the CH340 or from Silicon Labs for the CP2102, and plug the board in again.
ESP32 pinout
The pinout names every pin twice: the label printed on the board, such as D2, and the GPIO number, such as GPIO2, that the program uses. Hovering a pin, a part or a trace explains it. We keep it open whenever we wire to the board.
Step 3: Create the project
Click the PlatformIO icon, the alien head in the sidebar on the left, then Create New Project (under Quick Access, or PIO Home → New Project), and fill in the wizard:
| Field | Value |
|---|---|
| Name | blink |
| Board | Espressif ESP32 Dev Module |
| Framework | Arduino |
| Location | the default, or a folder of your own |
Neither the project name nor the path to its folder may contain Å, Ä or Ö. Parts of the build tools cannot read them and fail with errors that say nothing about the letter. The default location is Documents\PlatformIO\Projects in the Windows user folder, so if the user name contains one of the letters, untick Use default location and choose a folder such as C:\esp32.
Click Finish. PlatformIO creates the folder blink and opens it in VS Code (Figure 13.7.2). The first project takes a while because PlatformIO downloads the ESP32 platform in the background.
PlatformIO works only when VS Code has the project folder itself open, the folder that holds platformio.ini. With the folder above it open, or a single file, the buttons are missing or act on another project. To open a project, right-click its folder in the file manager and choose Open with VS Code (the Windows installer adds it; on Windows 11 it may sit under Show more options), or use File → Open Folder… in VS Code. Keep one project per VS Code window, and close it with File → Close Folder before opening the next.
test2, as the wizard made it. The numbers are explained in the text.
- Explorer: the project folder as a tree. It opens with
Ctrl+Shift+Eor the top icon of the sidebar. A click on a file opens it in the editor. - PlatformIO icon: the alien head, which opens the PlatformIO sidebar.
.pio: what PlatformIO downloads and builds. We never edit it. The other folders stay empty until a project grows (The project folder).src/main.cpp: the program. Step 5 replaces it.platformio.ini: how the project is built. Step 4 replaces it.- Editor: open files as tabs. Dragging a tab to the right half places two files side by side.
- Terminal: shows what PlatformIO does when it builds and uploads.
- Build: compiles the program.
- Upload: compiles and writes the program to the board.
- Serial Monitor: with the toolbar setting, opens Microsoft’s Serial Monitor (Step 7). Buttons 8–10 are used in Step 6.
Step 4: Replace platformio.ini
Open platformio.ini, delete everything in it and paste:
[env:esp32dev]
platform = espressif32@8.0.0
board = esp32dev
framework = arduino
upload_speed = 921600
monitor_speed = 115200Save the file. PlatformIO notices the change and prepares the project again, which the first time downloads the exact platform version named on the platform line.
That version number is the point of the file. The wizard writes platform = espressif32 without one (Figure 13.7.2), and PlatformIO then uses whichever version is already installed on the computer, or the newest one on the day the project is first built. Two students with the same code can therefore build two different programs. With @8.0.0, the newest version at the time of writing, every computer downloads and uses the same one, and the libraries a project needs are listed in the same file with their versions too (Libraries). platformio.ini line by line explains the other lines.
Step 5: Write the program
Open src/main.cpp, delete everything in it and paste:
#include <Arduino.h>
const int ledPin = 2; // the blue LED marked D2
const int blinkMs = 500; // time on, and time off
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
Serial.println("on");
delay(blinkMs);
digitalWrite(ledPin, LOW);
Serial.println("off");
delay(blinkMs);
}The program switches the LED on pin 2 on and off every 500 ms and reports each change to the computer. The program line by line goes through it.
Step 6: Build and upload
The PlatformIO toolbar is in the status bar at the bottom of the VS Code window (Figure 13.7.2). Its three buttons we use all the time are:
| Button | Action | What it does |
|---|---|---|
| ✓ | Build | Compiles the program. Nothing is sent to the board. |
| → | Upload | Builds if needed, then writes the program to the board. |
| plug | Serial Monitor | Opens the Serial Monitor (Step 7). |
Click Build. The first build downloads the compiler and the Arduino framework for the ESP32, a few hundred megabytes, and takes several minutes. It ends with SUCCESS. Later builds take seconds, because only changed files are compiled again.
Click Upload. The terminal first repeats the end of the build and then starts Connecting..., adding a dot for every attempt (Figure 13.7.3). While the dots are counting, press the BOOT button on the board briefly. The upload then usually starts: Writing at 0x... lines count up in percent and the terminal ends with SUCCESS.
Connecting.... is the moment to press BOOT.
The two bars above the upload lines report how much of the chip the program takes. Blink uses 21 kB of the 328 kB of RAM, 6.6 %, and 269 kB of the 1.3 MB of flash set aside for the program, 20.5 %. The RAM bar counts only the variables that exist from start-up; what the program allocates while it runs comes on top. Almost all of the flash is the Arduino framework and not our twenty lines, so a program many times longer still fits easily. The numbers are worth a glance when a project grows, since a program that runs out of RAM crashes while it runs, long after the build reported SUCCESS.
The ESP32 boards in our kits do not enter upload mode by themselves, so every upload needs a press on BOOT while the terminal shows Connecting.... If you miss the moment, the upload fails after a few seconds with Failed to connect to ESP32. Click Upload again and press BOOT during the dots. Why the button is needed is explained below. Boards with a good auto-reset circuit, and boards whose chip has USB built in, upload without the button.
After the upload the board restarts and the blue LED marked D2 blinks once per second (Figure 13.7.4).
D2 LED on GPIO 2 lit next to the red PWR LED.
Step 7: Watch the board in the Serial Monitor
Click the plug in the status bar. Without the toolbar setting, open the panel at the bottom of VS Code (Terminal → New Terminal) and click the Serial Monitor tab next to Terminal (Figure 13.7.5). Set:
- Port: the board’s COM port,
USB-SERIAL CH340for the boards in the lab kits - Baud rate:
115200, the number inSerial.begin() - Line ending:
LF
and click Start Monitoring. The board prints on and off in turn.
One character on the wire explains why the baud rate must match, and Reading a line what the line ending is for.
A COM port can be open in only one program at a time. While the Serial Monitor holds the port, an upload fails with PermissionError or Access is denied. Click Stop Monitoring, upload, then Start Monitoring again. The settings stay.
Step 8: Check that you own the setup
Change blinkMs to 100 at the top of main.cpp, upload again and watch the LED blink five times faster. If that worked, the setup is complete.
The next project
A new project is easiest made from a copy of one that works. Close the project in VS Code (File → Close Folder), copy the whole blink folder in the file manager, and rename the copy, for example to servo, again without Å, Ä or Ö. Delete the .pio folder in the copy, since PlatformIO makes it again at the first build. Open the copy as in Step 3, with Open with VS Code or File → Open Folder…. It builds at once with the same platform version and the same settings, and only main.cpp and, when the project needs libraries, platformio.ini change from there.
Troubleshooting
Is it the board or the setup?
Flash Blink from the browser in Chrome or Edge. The page writes the finished program without PlatformIO. If the LED then blinks, the board and the cable work, and the fault lies in the PlatformIO setup.
No COM port appears, or Upload says it cannot find a serial port
The computer does not see the board. Try another cable first, since a charge-only cable is the most common cause, then another USB port. Check Device Manager as in Step 2 and install the driver if the board shows up under Other devices.
Failed to connect to ESP32: Wrong boot mode detected or Timed out waiting for packet header
The board was not in upload mode when the computer tried to connect. Press BOOT while Connecting.... is shown, as described in Step 6.
could not open port 'COM5': PermissionError or Access is denied
Another program has the serial port open. Click Stop Monitoring in the Serial Monitor, close the port in Teleplot, and close every other program that may hold it, such as a second VS Code window or the Arduino IDE. Then upload again.
The serial monitor shows garbage characters
The monitor and the program use different baud rates. Choose 115200, the number in Serial.begin() in every project of this book (The wrong baud rate).
The plug still opens PlatformIO’s monitor
The toolbar setting is missing or broken. Open the user settings again and check that the block sits inside the outer { } with a comma between it and the line above. VS Code underlines a missing comma in red.
The board ignores what we type
The Serial Monitor’s Line ending is None. Set it to LF (Step 7).
The build fails after an extension update
Delete the hidden .pio folder in the project and build again. It holds only downloaded and generated files, and PlatformIO recreates it.
ModuleNotFoundError: No module named 'intelhex'
The build stops at bootloader.bin with a Python traceback that ends in
File "...\.platformio\packages\tool-esptoolpy\esptool\bin_image.py", line 16
from intelhex import HexRecordError, IntelHex
ModuleNotFoundError: No module named 'intelhex'
*** [.pio\build\esp32dev\bootloader.bin] Error 1
Our code compiled; the failure lies in esptool, the Python program that turns the compiled program into the image written to the board, and its installation is broken. Close VS Code, delete the folder
C:\Users\<your name>\.platformio\packages\tool-esptoolpy
then open VS Code and build again. PlatformIO notices that esptool is missing and downloads a fresh copy before the build.
How the Setup Works
Why PlatformIO
The Arduino IDE is the classic way to program boards like the ESP32. It keeps the board selection, the library versions and the port speed in global settings of the editor, outside the project folder, so a sketch that built last spring may not build this autumn because a library was updated in between. PlatformIO moves all of this into one text file inside the project, and it runs inside VS Code, which we already use for Python. The editor brings autocompletion, Git and an integrated terminal with it.
The project folder
PlatformIO creates this structure:
blink/
├── platformio.ini the project description
├── src/
│ └── main.cpp the program
├── include/ header files (.h) of our own
├── lib/ libraries of our own
├── test/ unit tests
├── .vscode/ editor settings, made by PlatformIO
└── .pio/ downloads and build output, never edit or commit
Only platformio.ini, src/ and the folders we put files in are part of the project. The .pio folder is rebuilt from platformio.ini whenever it is missing, which is why it is excluded from Git, why deleting it is a safe repair and why a copied project does not need it.
platformio.ini line by line
[env:esp32dev]-
Square brackets start a section. This one defines an environment called
esp32dev: one complete recipe for building the project for one board. The name is ours to choose; we name it after the board. The three lines that follow say what to build with: a platform, a board and a framework. platform = espressif32@8.0.0-
A platform is the set of tools for one family of chips: the compiler that translates C++ into the chip’s machine code, the uploader that writes the result into the chip, and the frameworks that run on it.
espressif32selects the one for Espressif’s ESP32 chips, and@8.0.0pins its version. Each platform version brings a specific version of everything inside it; 8.0.0 brings version 3.3.12 of the Arduino framework for the ESP32. With the version pinned, the code in this book builds the way it is printed. Moving to a newer version is a deliberate change of one line, made when we are ready to fix what it breaks. board = esp32dev-
A board is one particular circuit board built around a chip. This line tells PlatformIO which chip the board carries, how much flash memory it has, how fast the chip is clocked and how a program is uploaded to it.
esp32devdescribes the common ESP32 development board with an ESP-WROOM-32 module, which is ours; the full list is in the board registry. framework = arduino-
A framework is the library of functions the program is written against.
arduinogives us the Arduino functions (pinMode,digitalWrite,delay,Serial), which hide the registers of the chip behind a few readable calls and look the same on every board that Arduino supports. The alternative,espidf, is Espressif’s own framework, closer to the hardware and with far more to learn before the first LED blinks. upload_speed = 921600-
The baud rate used while writing the program to the board. The default is 460800; doubling it halves the upload time. If uploads fail half-way with a long cable, lowering this number is the first thing to try.
monitor_speed = 115200-
The baud rate at which PlatformIO’s own monitor listens, and
pio device monitorin the terminal. The Serial Monitor extension and Teleplot do not read the file, so in them we choose the number by hand.
Version 3 of the Arduino framework for the ESP32 removed the PWM functions of version 2: ledcSetup and ledcAttachPin became ledcAttach. Much example code on the web still uses the old names, and under our pinned platform it stops compiling with an error that the function was not declared. Such code builds once its calls are rewritten with ledcAttach.
Libraries
Libraries are declared in the same file, under lib_deps, by owner, name and version. The magnetic angle sensor used later in the course is read with Rob Tillaart’s AS5600 library:
lib_deps =
robtillaart/AS5600@^0.6.1PlatformIO downloads the library into .pio on the next build. The ^ accepts later bug-fix releases such as 0.6.4, but not 0.7, which is allowed to change how the library is used. Libraries are found in the PlatformIO registry, where each library page shows the exact line to paste.
The program line by line
#include <Arduino.h>The first line makes the Arduino functions known to the compiler. Lines that start with # are instructions to the preprocessor, which edits the text of the program before the compiler reads it, and #include pastes in the file Arduino.h, where pinMode, digitalWrite, delay, Serial and the names HIGH, LOW and OUTPUT are declared. The Arduino IDE adds this line silently; in PlatformIO we write it ourselves.
const int ledPin = 2; // the blue LED marked D2
const int blinkMs = 500; // time on, and time offEach line gives a number a name. int says that the name holds an integer, const forbids the program to change it, and the semicolon ends the statement, as it ends every statement in C++. The 2 is the GPIO number of the blue LED marked D2 (Figure 13.7.4). The text after // is a comment, which the compiler skips. Naming the numbers at the top keeps them in one place: changing the pin or the blink period means changing one line and uploading again. Much example code on the web names its pins with #define LED_PIN 2 instead, which does the same job.
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
}setup is a function, a named block of statements between braces. void says that it returns no value, and the empty parentheses that it takes no inputs. The board runs setup once each time it starts, after power-up or a press on EN. Serial.begin(115200) opens the serial connection to the computer over the USB cable at 115 200 baud, bits per second (Serial communication). pinMode(ledPin, OUTPUT) makes GPIO 2 an output. A pin starts as an input, which only senses a voltage; as an output it drives the pin to 3.3 V or to 0 V.
void loop() {
digitalWrite(ledPin, HIGH);
Serial.println("on");
delay(blinkMs);
digitalWrite(ledPin, LOW);
Serial.println("off");
delay(blinkMs);
}loop runs after setup, and again each time it reaches its closing brace, for as long as the board has power. We never call the two functions ourselves. The Arduino framework holds the code that runs first, and in effect it does this:
setup();
while (true) {
loop();
}digitalWrite(ledPin, HIGH) drives the pin to 3.3 V. Current flows from the pin through a 1 kΩ resistor and the LED on the board to ground, and the LED lights (Figure 13.7.6).
D2 LED, on the board itself. HIGH puts 3.3 V on GPIO 2 and the LED lights; LOW puts 0 V there and it goes dark.
Serial.println("on") sends the text on and a line break to the computer, where the serial monitor shows it. delay(blinkMs) makes the processor wait 500 ms and do nothing else meanwhile. The second half does the same with LOW, which drives the pin to 0 V, so the LED goes dark. One pass through loop takes 1000 ms, and the LED blinks once per second.
C++ tells upper-case and lower-case letters apart, so serial.begin or pinmode is a compile error. The compiler’s message names the line to look at first.
Why the BOOT button
The EN button holds the chip in reset while it is pressed, and the BOOT button connects GPIO 0 to ground. At the moment EN is released the chip reads GPIO 0 and decides what to run (Figure 13.7.7). If the pin is high, the chip runs the program in its flash memory. If the pin is low, it starts a small loader in its read-only memory that waits for a new program over the serial port.
Many boards have an auto-reset circuit: two transistors that let the USB chip pull GPIO 0 low and reset the ESP32 through the control lines of the serial port, so the uploader can enter upload mode by itself. Every dot after Connecting is one such attempt, a reset with GPIO 0 meant to be low.
The timing is tight. GPIO 0 must already be low when EN is released, and the circuit gets it right only with suitable components, among them a capacitor on the EN pin. On a board that saves on these parts, or uses values that do not match the USB chip, GPIO 0 goes low too late and the old program starts again, the middle case of Figure 13.7.7. That is the case with the boards in our kits. A capacitor of about 10 µF between EN and ground is the usual repair, and some boards upload without the button only after a modification. Some clones have no auto-reset circuit at all, and the button is then the only way in.
Pressing BOOT holds GPIO 0 low by hand across the reset, the lowest case of Figure 13.7.7. Once the loader has answered, the chip stays in upload mode until it is reset, so the button can be released. Boards with a chip that has USB built in, such as the ESP32-S3 on the XIAO, need neither the button nor an auto-reset circuit: the chip itself answers the uploader over the USB cable and enters upload mode on request.
GPIO 0 is also the reason the table in Which pins to use marks it, together with GPIO 2, 5, 12 and 15, as a pin to use with care. These strapping pins are read at reset, and a circuit that pulls one of them the wrong way prevents the board from starting or from accepting an upload.
Another board
The course also uses the Seeed Studio XIAO ESP32-S3, a much smaller board with an ESP32-S3 chip (Figure 13.7.8). Blink runs on it from a copy of the project with two changes.
EN and BOOT buttons beside the connector and the AMS1117 regulator above it. Right: the Seeed Studio XIAO ESP32-S3.
In platformio.ini the environment gets the new board:
[env:xiao_esp32s3]
platform = espressif32@8.0.0
board = seeed_xiao_esp32s3
framework = arduino
monitor_speed = 115200The upload_speed line is gone, since the XIAO uploads over its built-in USB, where the setting has no effect. In main.cpp, ledPin becomes 21, the GPIO of the XIAO’s LED. That LED is wired between 3.3 V and the pin, so it lights when the pin is driven LOW, and with the program unchanged it is dark while the monitor says on. Swapping HIGH and LOW in loop makes the two agree.
The XIAO connects its USB port directly to the ESP32-S3, which has USB built in, so it needs no USB chip, no driver and no BOOT button for a normal upload. If a program crashes so early that the board no longer shows up as a port, hold BOOT while plugging the cable in; the board then starts in upload mode and accepts a new program.
The same steps from a terminal
The toolbar buttons run PlatformIO Core commands, and the same commands work in the VS Code terminal (Ctrl+ö on Nordic keyboards). Run them in the project folder:
pio run # build the default environment
pio run -t upload # build and upload
pio device monitor # open the serial monitorOn Windows, the pio command is found when the terminal is opened from the PlatformIO sidebar (Quick Access → Miscellaneous → PlatformIO Core CLI).
The plug button opens Microsoft’s Serial Monitor
The plug button in PlatformIO’s toolbar (Step 6) opens PlatformIO’s own serial monitor. It writes our typing into the same stream as the board’s output, so a board that prints fast tears up the line we are typing and Backspace stops working. One user setting points the button at Microsoft’s Serial Monitor instead. The Windows installer writes it when PlatformIO for ESP32 is ticked. The setting belongs to the computer, so every project gets the same button.
Press Ctrl+Shift+P, run Preferences: Open User Settings (JSON), and paste the block below just before the last } of the file, with a comma after the line above it:
"platformio-ide.toolbar": [
{ "text": "$(home)", "tooltip": "PlatformIO: Home", "commands": "platformio-ide.showHome" },
{ "text": "$(check)", "tooltip": "PlatformIO: Build", "commands": "platformio-ide.build" },
{ "text": "$(arrow-right)", "tooltip": "PlatformIO: Upload", "commands": "platformio-ide.upload" },
{ "text": "$(trashcan)", "tooltip": "PlatformIO: Clean", "commands": "platformio-ide.clean" },
{ "text": "$(beaker)", "tooltip": "PlatformIO: Test", "commands": "platformio-ide.test" },
{ "text": "$(plug)", "tooltip": "Serial Monitor", "commands": "vscode-serial-monitor.monitor0.focus" },
{ "text": "$(terminal)", "tooltip": "PlatformIO: New Terminal", "commands": "platformio-ide.newTerminal" }
]The setting lists every button of the toolbar, so the block repeats PlatformIO’s own and changes only the plug’s command. Save the file; the toolbar picks up the change at once.

