Week 4: Embedded Programming¶
During this week, we began to formally engage with Embedded Programming. Embedded systems are at the core of many digital manufacturing projects—from sensor data collection to controlling motors, lights, or communication modules, all of which rely on the programming and debugging of microcontrollers.
Group assignment:
Understand different development environments and programming methods from an overall perspective, such as Arduino, MicroPython, ESP-IDF, etc. Observe their differences in usage, development experience, and programming logic through practical tests or simple example programs.
Individual assignment:
Select a microcontroller development board as the hardware programming platform. First, read the data sheet of the chip to understand its basic structure, including the chip architecture, storage structure, peripheral resources, and supported development environment. Then, use a simulation platform or real hardware to complete several basic experiments, such as controlling an LED, reading an input device (e.g., a button or sensor), and implementing a communication method (e.g., UART, I2C, SPI, or wireless communication).
Overall, the focus of this week is not to complete complex projects, but to build a basic understanding of microcontroller programming, including how to read chip datasheets, how to write a simple program, and how to enable the development board to interact with the outside world. Through these basic exercises, we will lay the foundation for subsequent electronic production and project development.
Group Assignment¶
Individual Assignment¶
1. Understanding ESP32: From Development Board to Chip Structure¶
Before starting embedded programming, it is first necessary to understand the hardware platform we are using. Only by understanding what resources are inside the microcontroller and how these resources work together can we utilize them more efficiently during actual development.
For this experiment, I chose to use ESP32 as the microcontroller platform. ESP32 is a system-on-chip (SoC) introduced by Espressif Systems, widely used in Internet of Things (IoT) devices, smart homes, and embedded control systems. It not only has strong computing capabilities but also comes with built-in Wi-Fi and Bluetooth communication modules, making it very common in maker and engineering projects.
To better understand the capabilities of the ESP32, I will start with the external structure of the development board and then gradually learn about the ESP-WROOM-32 module and the main internal modules of the chip.
1.1 Main Hardware Components of the Development Board¶
When you get an ESP32 development board, you can see that the board contains multiple basic hardware components, which together form the basic environment for development and debugging.
The most prominent part in the center of the development board is the ESP-WROOM-32 module . This module integrates the ESP32 main control chip and necessary peripheral circuits internally, responsible for performing core functions such as computing, control, and wireless communication.
The development board usually also includes the following important parts:
| Hardware Components | Function |
|---|---|
| ESP-WROOM-32 Module | Core Computing and Communication Module |
| USB / Type-C Interface | Provides power supply, program download, and serial communication |
| BOOT Button | Used to enter the program download mode |
| EN (Reset Key) | Restart the chip |
| GPIO Pin | Used to connect external devices |
Among them, the USB interface can simultaneously complete power supply, serial communication, and program downloading, so it is very convenient to use and does not require an additional programmer.
The pin headers arranged on both sides of the ESP32 development board are interfaces for connecting to the outside world. Among them, the most commonly used are GPIO (General Purpose Input Output) pins.
GPIO is a general-purpose digital input/output interface that can control its input or output state through a program. Through these pins, the ESP32 can connect to various external devices, such as: LED lights, buttons, temperature and humidity sensors, displays, motors, or relays
Through GPIO, the ESP32 can sense the external environment and control various devices.
1.2 ESP-WROOM-32 Module Structure¶
The most important part of the ESP32 development board is actually the ESP-WROOM-32 module. This module integrates the ESP32 chip and key peripheral components into a small module, making it more convenient for developers to use.

After disassembling the module, it can be seen that the interior mainly consists of four core components:
| Component | Function |
|---|---|
| Flash Memory | Stores program code and user data |
| Crystal Oscillator | Provides system clock |
| Antenna | is responsible for Wi-Fi / Bluetooth communication |
| ESP32 Chip | Perform all computational and control tasks |
These components together form a complete microcontroller system.
1.2.1 Flash Memory¶
On the ESP-WROOM-32 module, the flash memory is an independent small chip with a rectangular appearance, usually using SOP8 packaging. Its common model is CigaDevice 25Q128ESIG, and its position is adjacent to the ESP32 main chip.
The main function of this flash memory is to store program code and user data . When you burn code into the ESP32, you are actually writing the program into this flash memory chip. It communicates with the ESP32 chip via the SPI/QSPI interface , enabling both fast data reading and long-term content retention (non-volatile) even after power-off.
Additionally, this type of flash memory also has some important protection mechanisms, such as wear leveling , which can evenly distribute the locations of data writes (avoiding repeated erasure and writing in the same area), thereby extending the service life of the chip.
The common capacity of flash memory is 16MB. The larger the flash memory capacity, the more program logic and resource files (such as web pages, images, models, etc.) it can accommodate, thus affecting the richness of system functions and scalability.
1.2.2 Crystal Oscillator¶
On the ESP-WROOM-32 module, the crystal oscillator is a crucial small component, usually located near the ESP32 chip, with a rectangular metal shell and generally marked with frequency information on the surface, such as "40.000" or "YL400".
The main function of the crystal oscillator is to provide a basic clock signal for the ESP32, with common frequencies being 26MHz or 40MHz. It ensures the normal operation of the processor, wireless module, and peripherals, equivalent to setting a "metronome" for the entire system. This determines the operating speed of the ESP32's internal processor, the data transfer rate of the wireless module, and the working rhythm of many peripherals.

The crystal oscillator is connected to the ESP32 chip via a pair of pins and is usually also equipped with a pair of small capacitors (e.g., 12pF) to stabilize the oscillation signal. If these capacitors are not properly selected, it may lead to unstable oscillation frequency, which in turn affects the processor's operating speed, data transmission accuracy, and the reliability of wireless communication. Therefore, the stability of the crystal oscillator is crucial to the overall performance of the ESP32 and is a key component for ensuring the long-term reliable operation of the device.
1.2.3 Antenna¶
On the ESP-WROOM-32 module, the onboard antenna is located at the edge of the module. It is a section of copper foil trace etched on the PCB, with its surface covered by a black solder mask for protection, and it is serpentine in shape. Its main function is to capture and transmit wireless signals, especially 2.4GHz Wi-Fi and Bluetooth signals.
The antenna is responsible for converting the electrical signals generated by the ESP32 chip into electromagnetic waves for transmission, and at the same time converting the received electromagnetic waves back into electrical signals for the chip to process.
For example, when you use your phone to control a smart light via Wi-Fi, the wireless signal sent by the phone will be forwarded by the router to this antenna and then transmitted to the ESP32 chip for processing; conversely, when the ESP32 needs to send sensor data to the cloud, the antenna will also transmit the data.
Although the antenna design is simple, its length and structure must match the wavelength of the 2.4GHz signal to ensure optimal transmission performance. An unreasonable design may lead to signal attenuation or even disconnection. Additionally, the antenna needs to be kept away from the metal shielding and high-current paths on the module to avoid electromagnetic interference, so the onboard antenna is located at the edge of the module.
1.2.4 ESP32 Main Control Chip¶
At the center of the ESP-WROOM-32 module lies quietly a small square chip - this is the ESP32 main control chip . It is the core of the entire module, responsible for executing instructions, processing data, and exchanging data with components such as flash memory, crystal oscillator, and antenna through various interfaces, endowing the module with powerful computing and communication capabilities.
1.3 ESP32 Main Control Chip¶
The functionality of a chip basically determines the core capabilities of a microcontroller. The functional block diagram of the ESP32 chip is shown in the figure below. We will start with this functional block diagram and gradually analyze the internal structure of the chip.

From the overall structure, the core architecture of the ESP32 chip consists of a processor, storage unit, wireless communication module, encryption hardware, power management unit, and various peripheral interfaces. These modules are connected and work together via an internal bus.
Among them, the processor is responsible for computation and task scheduling, coordinating the work of other modules; the storage unit is the core of data access, divided into internal ROM and SRAM, as well as expandable external Flash and PSRAM, responsible for data access and task caching; the wireless communication module provides dual-mode functionality for Wi-Fi and Bluetooth. Wi-Fi is responsible for long-range high-speed data transmission, while Bluetooth has an advantage in short-range, low-power communication, with the two working in synergy; the power management unit and low-power module ensure that the chip maintains a low energy consumption level in both operating and standby states by dynamically adjusting power consumption; However, the peripheral interface module provides a variety of connection methods, such as SPI, I2C, UART, etc., facilitating data interaction with external sensors and actuators.
The overall structure of the ESP32 chip is not a simple stacking of modules, but rather the parallel existence and mutual cooperation of each module, jointly achieving efficient and stable chip operation.
1.3.1 CPU Processor¶
The processor is the computational core of the ESP32, determining the chip's processing speed and multitasking capabilities. The ESP32 uses the Xtensa® 32-bit LX6 architecture, supporting both single-core and dual-core configurations. In the dual-core architecture , the ESP32 is equipped with two cores: "PRO CPU" and "APP CPU". These two cores are basically identical in hardware structure, each having independent instruction and data buses, and can process their own instructions and data respectively. They can work simultaneously, support parallel processing of tasks, or execute tasks independently.



The greatest advantage of the dual-core architecture lies in its parallel processing capabilities, which can execute multiple tasks simultaneously, thereby improving overall operational efficiency. For example, in smart speaker applications, the PRO CPU can focus on processing voice data, while the APP CPU is responsible for Wi-Fi communication, with the two operating without interfering with each other. In this way, even if one task encounters a blockage, the other core can still operate normally, ensuring system stability.
The single-core version has only one core and is suitable for applications with low requirements for performance and power consumption. Whether single-core or dual-core, ESP32 can flexibly meet the needs of different scenarios.
1.3.2 Storage Unit¶

The storage unit determines how much program and data the chip can store, as well as how fast it can access this data.
The storage architecture of ESP32 is mainly composed of internal storage and external storage. They work together through the Memory Management Unit (MMU) and Cache system to ensure that the chip can efficiently run programs, access data, and meet the requirements of low power consumption at the same time.
1.3.2.1 Internal Storage¶
Internal storage section includes ROM and SRAM, located inside the chip.


(1) ROM (Read-Only Memory)
ROM is a non-volatile memory, meaning that the data stored inside will not be lost due to power outage. With a total capacity of 448KB, it is divided into two regions (384KB and 64KB), and it is mainly used to store the code that must be run during chip startup, low-level firmware, and system function libraries, which ensure that the chip can operate normally every time it is powered on. The data in ROM is written at the time of manufacture and cannot be modified by users, so it is very suitable for storing fixed and important program code.
ROM (Read-Only Memory)
- Total Capacity:448KB
- Partition:
- 384KB(Internal ROM 0)
- 64KB(Internal ROM 1)
- Function:
- Code for the Bootloader required to start the memory chipBootloadercode
- Includes underlying firmware and system function libraries, such as the commonly usedESP-IDF function
- Cannot be modified , the data is solidified at the factory and will not be lost when power is cut off
- Typical Use: Boot code, basic chip initialization function
(2) SRAM (High-Speed Volatile Memory)
SRAM is a type of high-speed volatile memory in the ESP32, meaning that its data read and write speeds are extremely fast (in the nanosecond range), and data will be lost when power is turned off. The total capacity is 520KB, divided into three parts (192KB, 128KB, 200KB). It is mainly used for temporarily storing data during program execution, such as variables, task stacks, and runtime caches. It is primarily used for temporary data storage during program operation, such as variables, task stacks, and caches. Due to its fast access speed, the processor can quickly read and write data, ensuring the efficient execution of programs.Since the data in SRAM cannot be stored persistently, it is suitable for storing data that needs to be read and written frequently but does not need to be stored for a long time.
Through different types of SRAM, ESP32 can select appropriate memory regions to store data according to different sleep modes, thereby reducing power consumption and improving system efficiency.
SRAM (High-Speed Volatile Memory)
- Total Capacity: 520KB
- Partition:
- 192KB(Internal SRAM 0)
- 128KB(Internal SRAM 1)
- 200KB(Internal SRAM 2)
- Function:
- Stores temporary data during program execution
- includes task stack, global variables, data buffer, etc.
- can serve as a data buffer for DMA
- Typical Uses: Local variables in programs, task stacks, temporary data caches
After learning about the basics of ROM and SRAM, everyone may wonder why they are divided into several different regions ?
First, it is necessary to clarify that the partitions here are not randomly divided, but rather to ensure that different system function codes can have their own dedicated spaces, avoiding mutual interference.
The total capacity of ROM is 448KB, which is divided into two areas: 384KB and 64KB.
For example, the 384KB section in ROM is dedicated to storing startup code, ensuring that the chip can start smoothly every time it is powered on; while the 64KB section is used to save the underlying system functions, ensuring that other programs can run normally. This partitioning allows the system to operate more systematically, preventing code and data from becoming confused, and also facilitating chip designers to optimize and protect the system;
SRAM is divided into three regions of different sizes, which not only meet the program's need for temporary data storage but also support the chip to enter different sleep modes. For example, when the device enters a low-power state, only a portion of the memory is used to store necessary data, which not only saves power but also ensures that data is not lost.
Storage partitions are a crucial aspect of chip design, helping the ESP32 find the optimal balance among speed, stability, and energy consumption.
1.3.2.2 External Storage¶
External storage componentsprimarily consist of extended Flash and PSRAM, which are located outside the chip and connected to the chip via SPI or QSPI interfaces.

(1) Flash (Flash Memory)
In the previous section on disassembling the module, we mentioned that the Flash of the ESP32 is an independent small chip, usually packaged together with the ESP32 main chip in the module, and belongs to non-volatile memory, where data will not be lost after power-off. It is mainly used to store user programs, file systems, static resources, and some critical system data, such as boot code and Wi-Fi configuration.
External Flash Memory
- Capacity:Typically 4MB to 16MB
- Function: Stores user programs, file systems, and static resources, with data remaining intact after power loss
- Features:Non-volatile storage, fast read speed, suitable for long-term data storage
- Application Scenarios:Program code storage, web file system, configuration data storage
(2) PSRAM (High-speed and High-capacity Storage)
PSRAM is a high-speed random access volatile memory with common capacities of 4MB or 8MB. It is mainly used to store large amounts of data that require frequent read and write operations, such as image cache, Machine Learning models, or real-time sensor data. Although its access speed is slightly slower than SRAM, it has a larger capacity and is well-suited for applications that require a large amount of memory.
External PSRAM
- Capacity: 2MB - 8MB
- Function: Expand large-capacity data storage to meet complex algorithms and data-intensive applications.
- Features: Large capacity, but relatively slow access speed, requiring additional hardware support.
- Application Scenarios : Image Processing, Speech Recognition, Big Data Caching.
1.3.2.3 Address Mapping and Caching¶
In a complex microcontroller like ESP32, the processor needs to frequently access various storage units, including internal ROM and SRAM and external Flash and PSRAM . However, the physical addresses of these memories vary, and direct access would be very cumbersome.
To solve this problem, ESP32 adopts the design ofunified address space. The so-called unified address space means mapping all storage unitsto a continuous virtual address range. In this way, regardless of whether the data is stored internally or externally, the processor can access it through this unified address space.
The key components for achieving this unified access are the Memory Management Unit (MMU) and Cache . They are responsible for mapping data stored externally to the unified address space, accelerating access speed, and ensuring that data can be transferred to the processor more quickly.
Small tip: The design of the unified address space means that all different types of memory (such as ROM, SRAM, Flash, PSRAM) share a continuous address range, and the processor can access all memory through this unified address space.
(1) Memory Management Unit (MMU)
The main task of the MMU is to map the physical addresses of external storage (such as Flash and PSRAM) to a unified virtual address space. This way, regardless of whether the data is stored internally or externally, the processor can access it through a unified address space, simplifying the data access process. This mapping mechanism not only simplifies data access but also allows us to write code without having to worry about the underlying physical addresses.
In addition, the MMU also allows flexible allocation and management of storage space, such as mapping the same physical storage area to different virtual address ranges, and can also perform memory protection according to program requirements. For example, the MMU of ESP32 can handle 24-bit addresses (up to 16MB Flash) and 23-bit addresses (up to 8MB PSRAM), which enables it to flexibly switch between different memories.
Physical addresses are the actual addresses on the memory chip, while virtual addresses are the addresses "seen" by the processor when executing a program.
Why is a unified address space needed? This is because when a processor executes instructions and accesses data, it usually only recognizes addresses , rather than the specific type of memory. If each type of memory has its own independent address space, then the processor would need to additionally determine which type of memory the data is stored in during each access, which not only increases the complexity of hardware design but also reduces access efficiency.
Take a simple example If there is no unified address space, the data accessed from ROM may range from 0x0000_0000 to 0x0007_FFFF, the data accessed from SRAM ranges from 0x2000_0000 to 0x2007_FFFF, and the data accessed from Flash ranges from 0x4000_0000 to 0x40FF_FFFF. During operation, the processor needs to frequently switch address spaces, which not only wastes time but also makes it error-prone.
After adopting a unified address space, the data in these memories can be mapped to a continuous address range, such as from 0x0000_0000 to 0x4FFF_FFFF. This makes it much simpler for the processor to access, as it only needs to remember a unified address range without having to worry about where the underlying data is specifically stored in which type of memory.
(2) Cache
Since the read and write latency of external memory is higher, the speed of accessing external storage is generally much slower than that of accessing internal storage. To reduce this latency, ESP32 introduced the "Cache" system.
Cache is a small-capacity but extremely fast storage area specifically designed to temporarily store frequently accessed data. Its basic principle is that when the processor accesses a certain piece of data, it first checks whether this data is in the cache. If it is, it can be directly read, greatly reducing the waiting time. If the data is not in the cache, it will then access the external storage and temporarily store the read data in the cache for subsequent quick access.
This mechanism of " caching first, then external storage " significantly improves the efficiency of the processor, because in practical applications, most data access is often "local" or "repetitive", meaning that certain data will be frequently accessed within a short period of time. Caching effectively utilizes this characteristic, reducing the time the processor spends waiting for external storage responses and improving the overall system response speed.
1.3.2.4 Typical Process of Memory Access¶
After understanding the basic principles of address mapping and caching, let's take a look at a typical memory access process of the ESP32.
First, when the processor needs to execute an instruction stored in external Flash, the MMU maps the physical address of this instruction to a virtual address space. Next, the processor first checks whether this instruction already exists in the cache. If the instruction is found in the cache, the processor can execute it directly, significantly reducing the instruction fetch time. If the instruction is not in the cache, the processor must access the external Flash, load the instruction into the cache, and then execute it.
Not only instructions, but also various temporary data , such as global variables, function call parameters, buffer data, etc., are frequently accessed by the CPU during operation. The access process for this data is basically similar to that of instructions, first going through MMU address mapping and then being accelerated by the cache.
Additionally, for some data that requires frequent and large-scale transmission, such as image data, audio streams, or sensor data, ESP32 also supports "DMA (Direct Memory Access)" channels. The characteristic of DMA is that it can directly transfer data between external storage and internal SRAM without occupying the CPU. In this way, the CPU can focus on computational tasks without being slowed down by large amounts of data transmission, greatly improving the overall efficiency of the system.
In summary, the MMU implements address mapping, the cache provides fast access, and DMA further optimizes the transfer of large data volumes. These mechanisms together constitute the efficient data access architecture of the ESP32, which is the key to achieving its high performance.
- MMU: Maps the physical addresses of external storage to a unified virtual address space
- Cache: Reduces the waiting time when accessing external storage
- DMA: Accelerates the transfer of large chunks of data and reduces CPU load
1.3.3 Wireless Communication Module¶
The wireless communication module of ESP32 consists of two main parts:Wi-Fi module and Bluetooth module.
Wi-Fi modules support devices to connect to wireless local area networks, enabling long-distance data transmission, and are commonly used in applications such as smart home, Internet of Things (IoT), and remote monitoring; Bluetooth modules include traditional Bluetooth and Bluetooth Low Energy (BLE), suitable for data exchange between short-range devices, and are widely used in smart wearable devices, wireless sensors, and portable audio devices.
The reason why ESP32 can achieve Wi-Fi and Bluetooth communication is not only dependent on the external antenna but also requires the complex wireless communication module inside the chip.



The Wi-Fi module consists of two core components: Wi-Fi MAC (Media Access Control layer) and Wi-Fi baseband processor. The MAC layer is responsible for managing the timing and sequence of data transmission, as well as coordinating transmissions with other devices in the same network to prevent signal conflicts and congestion; the baseband processor is responsible for converting digital signals into analog signals suitable for wireless propagation, or demodulating received analog signals into digital signals, thereby achieving the conversion between wireless signals and digital data.


ESP32 supports both Classic Bluetooth and Bluetooth Low Energy modes, and the Bluetooth module is also composed of a Link Controller and a Baseband Processor. The Link Controller manages the pairing, connection, and disconnection of Bluetooth devices; the Baseband Processor is responsible for the modulation and demodulation of Bluetooth signals, which is similar to the function of the Wi-Fi Baseband Processor, both of which convert between digital signals and wireless signals, just applied to different wireless protocols. These modules work together to enable ESP32 to achieve high-speed and low-power wireless communication in the 2.4GHz band, supporting both Wi-Fi and Bluetooth dual-mode functionality.

1.3.4 Encryption Hardware Acceleration Module¶
The ESP32 has a built-in cryptographic hardware acceleration module to accelerate common encryption and decryption operations. It supports a variety of commonly used cryptographic algorithms, including AES (Advanced Encryption Standard), SHA (Secure Hash Algorithm), RSA (Asymmetric Encryption Algorithm), and Random Number Generator (RNG). These modules can provide faster and more secure cryptographic processing when handling sensitive data, and are commonly used in wireless communication, authentication, and data protection, making devices more secure and reliable.

AES is a symmetric encryption algorithm widely used for data encryption. It performs encryption and decryption operations using the same key, is fast, and is suitable for protecting large amounts of data.

SHA is a class of hash algorithms used to generate a "fingerprint" or digest of data. It ensures data integrity and is also commonly used to verify passwords and digital signatures.

RSA is an asymmetric encryption algorithm that uses a pair of public and private keys for encryption and decryption. It is suitable for authentication and secure key exchange.

RNG, on the other hand, is a random number generator that provides high-quality random numbers and supports the need for unpredictability in cryptographic key generation and secure communication.

These hardware acceleration modules enable the ESP32 to perform encryption operations faster, more energy-efficiently, and more securely than pure software implementations, and they are an important foundation for achieving secure communication and data protection.
1.3.5 Power Management and Low-Power Module¶
In many IoT projects that require long-term operation but cannot frequently replace batteries, battery life is particularly important. The ESP32 is designed with full consideration of power consumption optimization, integrating multiple dedicated hardware modules, including PMU (Power Management Unit), ULP (Ultra-Low Power Coprocessor), Recovery Memory, and supporting multiple low-power modes, making it highly suitable for battery-powered IoT devices.


The PMU is responsible for managing the power supply status of the chip, dynamically adjusting voltage and clock frequency according to different operating modes to reduce overall power consumption. It can turn off some functional modules when the chip is idle to further save energy.

The ULP (Ultra-Low-Power) coprocessor is an independent low-power subsystem capable of running simple tasks, such as sensor Data Acquisition or timed wake-up, while the main CPU is in sleep mode. This can reduce the wake-up frequency of the main processor and significantly extend battery life.


Recovery Memory is a small memory area specifically designed to store critical data in low-power mode. Even during deep sleep, this part of the memory can retain data without loss, ensuring that the device can quickly resume its working state after waking up.
With this hardware support, ESP32 can flexibly switch operating states in different application scenarios, achieving longer battery life. So, what specific low-power modes does it have, and under what circumstances are these modes used?
The low-power modes of ESP32 mainly include the following five types:
- Active Mode: The processor operates normally, and all peripherals and wireless modules can run fully, which is the state with the highest power consumption.
- Frequency Modulation Mode : A low-power strategy in active mode that can dynamically adjust CPU frequency based on the load of the current task, reducing energy consumption without significantly affecting performance.
- Light Sleep Mode: The processor pauses operation, most peripherals are turned off, and only the low-power clock and necessary peripherals are retained.
- Deep Sleep Mode: ESP32 almost completely shuts down all peripherals, only retaining RTC memory and RTC peripherals. The main CPU is completely powered off, and only specific events (such as RTC timing, interrupt signals) can wake up the system. This mode has extremely low power consumption and is suitable for scenarios where tasks do not need to be processed for long periods, such as environmental sensor nodes or periodic data acquisition devices.
- Hibernation Mode : More aggressive than deep sleep, it retains only a very small amount of state information, almost completely shuts down the chip, and can only be woken up by pins or RTC. It is the state with the lowest power consumption of ESP32.
After the ESP32 enters the low-power state, how can it automatically resume normal operation when needed?

Under these five low-power modes, the ESP32 relies on the built-in RTC (Real-Time Clock) module to manage wake-up. The RTC is an independent small module that continues to operate even in deep sleep or sleep mode, and automatically wakes up the ESP32 at a set time point or when a specific event occurs, enabling the device to resume operation on demand.
1.3.6 Peripheral Resources¶
ESP32 not only has powerful computing capabilities but also can interact with external devices through its rich peripherals. The ESP32 chip integrates various peripheral modules internally, with the help of which it can perform multiple functions such as collecting sensor data, controlling motors, and completing signal conversion, making it an important component for realizing intelligent control.
| Peripheral Name | Function Description | Typical Application Scenarios |
|---|---|---|
| GPIO | General Purpose Input/Output (GPIO) Pin | Control LED, read button status, drive relay |
| ADC | Analog-to-Digital Converter | Read temperature sensor and light intensity |
| DAC | Digital-to-Analog Converter | Generate audio signals and control analog servos |
| PWM | Pulse Width Modulation | LED Dimming, Motor Speed Regulation |
| UART | Universal Asynchronous Receiver/Transmitter | Connect the GPS module and debug serial port |
| I2C | Two-wire low-speed serial communication | Drive the OLED screen and connect the temperature and humidity sensor (BME280) |
| SPI | Four-wire high-speed serial communication | Connect SD card, high-speed sensors (such as IMU) |
| I2S | Audio Data Transmission Interface | Connect the microphone and audio decoding chip |
| Watchdog | Anomaly detection, automatic restart when the system is abnormal | Prevent program freezes and ensure long-term stable operation of the device |
| ...... | ...... | ...... |
These functions will be mapped to GPIO, which in turn exposes these functions to the outside through its pins for us to use.
As can be seen from the pinout diagram, the ESP32 has a total of 34 GPIO pins, among which4 (GPIO34 - GPIO39) can only be used as inputs, and the remaining 30 can be used for both input and output. Peripheral resources such as ADC and DAC are also distributed among these pins, so when selecting pins, it is necessary to make a reasonable choice based on the requirements of specific functions.

In addition, the ESP32 is also equipped with timers and an interrupt system, which help it quickly respond to external events and ensure the precise execution of tasks. Through the timer and interrupt mechanisms, it can handle various emergencies and precisely control the timing of task execution.
- Timer: A timer is a mechanism that can trigger a specific operation after a set time. The ESP32 has multiple internal timers that can precisely control time and are suitable for performing periodic tasks. For example, you can use a timer to control reading sensor data every 1 second or periodically update the display content.
- Interrupt System: When an important event occurs, the interrupt system immediately interrupts the current task and instead prioritizes handling the new event. Just like the human emergency response mechanism, it helps the ESP32 quickly respond at critical moments.


1.4 Development Methods of ESP32¶
ESP32 offers a variety of development methods, each suitable for different development needs and scenarios. The following are several common development methods, including MicroPython, Arduino (including Arduino IDE and VSCode + PlatformIO), and the official ESP-IDF.
1.4.1 MicroPython Development Approach¶
MicroPython is a lightweight Python implementation designed for embedded systems, particularly suitable for beginners who want to quickly experience controlling hardware.
Target Audience: Beginners with a basic understanding of Python who want to quickly get started with hardware programming.
Development Tools : Thonny IDE is commonly used, with a simple interface and easy to get started, just like writing Python scripts.
Features and Highlights:
- Supports interactive REPL mode , where you can immediately see the hardware's response after entering a line of code;
- The development process is very lightweight, eliminating the need for cumbersome compilation and programming, allowing you to run the code as soon as you finish writing it , making it highly suitable for learning while trying.

1.4.2 Arduino Development Approach¶
Arduino is an open-source electronics platform widely used in the development of various electronic projects, providing a rich set of libraries and example code to help developers get started easily.
Suitable for : Beginners and developers who need rapid prototyping.
When developing using the Arduino framework, the following tools can be used:
- Arduino IDE: Arduino's official Integrated Development Environment, simple and easy to use, supporting development boards such as ESP32 and ESP8266.
- VSCode + PlatformIO:
- VSCode (Visual Studio Code) is a free and open-source code editor developed by Microsoft.
- PlatformIO is an embedded development platform that can be used in VSCode, providing more powerful editing, debugging, and version control capabilities, suitable for developers with some experience.
- Using VSCode + PlatformIO allows you to enjoy the powerful features of VSCode, such as code editing, debugging, version control, etc., while also being able to utilize the libraries, compilers, and upload tools provided by PlatformIO.
Feature: Through Arduino libraries and example code, developers can quickly get started.
1.4.3 ESP-IDF Development Approach¶
ESP-IDF is an IoT development framework officially provided by Espressif Systems. Based on C/C++, it offers a complete SDK for the ESP32 chip and is the most fundamental and native way to develop ESP32. Through this framework, you can directly control the ESP32's hardware, manage multi-threading, implement low-level operations, etc., and it is typically suitable for more complex projects that require precise control of hardware functions.
2. Simulation website Wowki¶
Wokwi is a browser-based simulation platform that allows users to write, debug, and run ESP32 code. It supports various virtual hardware, such as LEDs, buttons, sensors, etc., enabling users to simulate real-world hardware projects. Wokwi provides a user-friendly interface, making it easy for even beginners to get started.
2.1 Why Choose Wokwi?¶
1. No software installation required: Only a browser is needed, no need to download or install any software.

2. Supports multiple microcontrollers: Arduino series, ESP32 series, STM32 series, Raspberry Pi Pico

3. Abundant simulation capabilities: Supports multiple virtual hardware

4. Projects can be saved to the cloud: Users can access and manage projects anytime, anywhere, and share them with others via a link for easy collaboration. Click "Copy" to send the share, and can download the simulated files at any time.

5. Professional Features (Wokwi Pro): Wokwi Pro provides users with more powerful editing, debugging, and automated testing capabilities through deep integration with mainstream development tools, further enhancing development efficiency and experience.

6. Wokwi for VS Code: Wokwi integrates into Visual Studio Code (VS Code), providing more powerful editing and debugging capabilities. Users can directly write, debug, and run simulation code in VS Code.

7. Wokwi for CI: Wokwi for CI supports the continuous integration (CI) process, helping developers automate testing and deploying simulation projects. It is suitable for hardware simulation testing in DevOps processes.

8. Wokwi for JetBrains, Wokwi integrates into JetBrains' family of IDEs (such as IntelliJ IDEA, PyCharm, CLion, etc.), providing a seamless development and simulation experience.

2.2 Get Help and Resources¶
- Documentation and Tutorials: Wokwi provides detailed documentation and tutorials to help users get started quickly.
- Community Support: Join the Wokwi community to communicate with other developers, get help, and share projects.
- Real-time debugging : Allows real-time viewing of the code's running effects, enabling debugging and modification.

3. Conduct ESP32 simulation experiments on Wokwi¶
3.1 Light up the LED¶
Here, we connect an external LED to replace the onboard LED. Connect the long leg of the LED to GPIO12 of the ESP32, and connect the short leg of the LED to GND.

Next, we will write code to make the ESP32 control the output of high and low levels on pin 12 to light up and turn off the LED.
Take two steps: first, set pin 12 to output mode, then control pin 12 to output high and low levels.
Step 1: Set the pin mode
Since the GPIO pins of the ESP32 can both receive input signals and output control signals, we first need to tell it what this pin is for, which requires setting the "pin mode".
Step 2: Control the output of high and low levels on the pins
Control the output of pin 12 to high level through thedigitalWrite()function. The first parameter is also the pin number, and the second parameter is the output level, with high level beingHIGHand low level beingLOW.
We control the LED to turn on and off once every 1 second, repeating this cycle.
To implement this function, simply add a delay function after each statement that controls the level of the control pin.delay(1000) Its function is to make the program "pause" for 1000 milliseconds, which is equivalent to 1 second.
int ledPin = 12; // 定义LED连接的GPIO引脚
void setup() {
pinMode(ledPin, OUTPUT); // 设置为输出模式
}
void loop() {
digitalWrite(ledPin, HIGH); // 输出高电平,点亮LED
delay(1000); // 延时1秒
digitalWrite(ledPin, LOW); // 输出低电平,熄灭LED
delay(1000); // 延时1秒
}
Click to upload the code, and you will see that the LED light blinks once every 1 second.

3.2 Sliding Potentiometer¶
A slide potentiometer is essentially the same as a rotary potentiometer, both being variable resistors. The only difference is that a slide potentiometer does not rotate but instead pushes or pulls a slider , making it more suitable for intuitive adjustment, such as creating a volume slider, a light dimmer, etc.
It also has three pins, and the connection method is as follows:


We enter the following code:
void setup() {
Serial.begin(115200); // 初始化串口
}
void loop() {
int val = analogRead(34); // 读取滑动电位器的电压
Serial.println(val); // 打印值
delay(200); // 等一等,别刷太快
}
can then read the voltage value of the sliding potentiometer in real time and display it via the serial monitor.

3.3 UART Communication¶
UART (Universal Asynchronous Receiver/Transmitter) is one of the commonly used communication methods for microcontrollers, which enables the ESP32 to exchange data with computers, other microcontrollers, or external modules. Through UART, we can send commands, receive sensor data, or use serial debugging programs, which is very convenient.
The ESP32 development board comes with a built-in hardware serial port, and we usually operate it through the Serial object.
When using the serial port, it generally involves the use of these key functions: the serial port initialization function Serial.begin(), the data output functions Serial.print() and Serial.println(), and the data reception functions Serial.available() and Serial.read().
To enable the ESP32 to send program running status or data to the computer, the serial port needs to be initialized first, which means telling the ESP32 and the computer "the speed and manner of communication". This process is completed using Serial.begin(). For example:
Once the serial port is opened, data can be sent out. The most commonly used functions are Serial.print() and Serial.println(). Serial.print() prints data without a newline, while Serial.println() automatically adds a newline after printing. They can print strings, characters, integers, floating-point numbers, etc., and can also specify output formats, such as hexadecimal, binary, or the number of decimal places for floating-point numbers.
Sample code:

ESP32 can not only "speak", but also "listen".Serial.available() is used to check if there is data in the serial buffer. If the return value is greater than 0, it means data has come in;Serial.read() reads one ByteDance at a time. As a simple example, we can make ESP32 receive characters sent by the computer byte by byte and print them out:
void setup() {
Serial.begin(115200);
}
void loop()
{
if (Serial.available() > 0)
{
char received = Serial.read(); // 读取一个字节
Serial.print("Received: ");
Serial.println(received); // 打印接收到的字符
}
}


Why is there an extra line of "Received: " printed here? This is because line breaks and carriage returns were not ignored. We will modify the code to make adjustments and continue to observe:
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available() > 0) {
char received = (char)Serial.read();
if (received != '\n' && received != '\r') { // 忽略换行和回车
Serial.print("Received: ");
Serial.println(received);
}
}
}

After removing line breaks and carriage returns, it is now normal.