yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
ESP32 Core Board📖
1. ESP32 Introduction
  • 1. ESP32S3 Overview
  • 2. Environment Setup Introduction
  • 3. Dev Board Introduction
2. ESP-IDF Development Tutorial
1. Before Development
  • 1. Environment Setup (Windows)
  • 2. Environment Setup (Linux)
  • 3. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. DMA
  • 8. ADC
  • 9. PWM Breathing LED
  • 10. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. PSRAM External Memory Experiment
  • 5. Flash Read and Write Experiment
  • 6. USB Emulated Mass Storage Experiment
4. FreeRTOS operating system
  • 1.FreeRTOS Core Concepts Theory
  • 2.Task Creation and Management
  • 3.Queue
  • 4.Binary Semaphore
  • 5.Mutex
  • 6.Event Groups
  • 7.Software Timer
  • 8.Task Scheduler
  • 9.Low Power Mode
  • 10.Deadlock
  • 11.Priority Inversion
5. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. Socket Programming Basics
  • 9. HTTP Client Experiment
  • 10. HTTP Server Experiment
  • 11. MQTT IoT Communication Protocol
  • 12. WIFI OTA Upgrade
  • 13. Bluetooth Fundamentals
  • 14. Bluetooth Slave Mode
  • 15. Bluetooth Master Mode
6. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
7. Xiaozhi AI Voice
  • 1. Burn Xiaozhi Firmware
  • 2. Network and Configuration
  • 3. AI Agent Settings
  • 4. Program Analysis
  • 5. Free Chat
3. Arduino Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. ADC
  • 8. PWM Breathing LED
  • 9. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication
  • 2. I2C OLED Display
  • 3. SPI Bus Communication
  • 4. Flash Read and Write
  • 5. USB Emulated Mass Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Server Experiment
  • 5. UDP Client Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT IoT Communication Protocol
  • 11. WIFI OTA Upgrade
  • 12. Bluetooth Fundamentals
  • 13. Bluetooth Slave Mode
  • 14. Bluetooth Master Mode
5. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
4. MicroPython Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
  • 3. Thonny IDE
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. TIMER_IT
  • 5. Watchdog Timer
  • 6. ADC
  • 7. PWM Breathing LED
  • 8. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. Flash Read and Write Experiment
  • 5. Print Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT
  • 11. Bluetooth Fundamentals
  • 12. Bluetooth Slave Mode
  • 13. Bluetooth Master Mode
5. Audio Applications
  • 1. I2S Audio Playback Experiment
  • 2. Repeater Experiment
Download
  • Code
  • Hardware_Info
  • 3D_Model_File
  • Software_Tools
  • VMware
  • VM_File
Download ZIP

Welcome to ESP32 Core Board repository

1. WIFI Network Basics

WIFI Network Basics


WIFI Network Basics1. Electromagnetic Waves and Wireless Communication1.1 What Are Electromagnetic Waves1.2 Why WiFi Uses 2.4 GHz2. How WiFi Works2.1 Channels2.2 RSSI (Signal Strength)2.3 Evolution of the 802.11 Protocol Family2.4 WiFi Security Authentication3. WiFi Operating Modes3.1 STA Mode (Station)3.2 AP Mode (Access Point)3.3 STA + AP Hybrid Mode3.4 STA vs AP Comparison4. ESP32-S3 WiFi Hardware Features5. ESP32-S3 WiFi Development Essentials5.1 Resource Conflict Between WiFi and ADC25.2 NVS — WiFi's Storage Dependency5.3 Fixed WiFi Initialization Order5.4 Antenna5.5 Strapping Pins5.6 WiFi Event-Driven Model5.7 EventGroup Synchronization Mechanism6. WiFi OTA Firmware Upgrade6.1 What Is OTA6.2 Flash Partition Layout6.3 OTA Upgrade Process6.4 Version Extraction — Magic Number Search Method6.5 OTA Core APIs6.6 Firmware Server6.7 OTA Notes7. WiFi Common Problem TroubleshootingCommon Network Communication Protocols1. The TCP/IP Protocol Stack1.1 The Layered Model1.2 Data Encapsulation Process1.3 Key Protocol Comparison2. IP Address2.1 IPv4 Basics2.2 Subnet Mask2.3 Public IP vs Private IP2.4 Special IP Addresses3. Ports3.1 The Concept of Ports3.2 Client Port vs Server Port4. Socket Programming Basics4.1 What Is a Socket4.2 Key Data Structures4.3 Network Byte Order4.4 Socket Creation Types5. TCP in Depth5.1 Three-Way Handshake5.2 Four-Way Termination5.3 How Reliable Transmission Is Implemented5.4 The Three Return Cases of recv()5.5 Standard TCP Server Flow6. UDP in Depth6.1 The Meaning of Connectionless6.2 UDP Suitable Scenarios6.3 UDP vs TCP API Comparison6.4 Non-Blocking Receive (MSG_DONTWAIT)7. HTTP Protocol Basics7.1 Request Format7.2 Response Format7.3 Common Status Codes7.4 Common HTTP Methods8. MQTT Protocol Basics8.1 Why IoT Uses MQTT Instead of HTTP8.2 Publish/Subscribe Model8.3 Topic Wildcards8.4 The Three QoS Levels9. ESP-IDF Network API Selection Guide10. Common Debugging Methods10.1 Troubleshooting Steps10.2 Common Debugging Commands11. Common Network Problems


1. Electromagnetic Waves and Wireless Communication

1.1 What Are Electromagnetic Waves

The essence of WiFi is electromagnetic waves — a changing electric field generates a magnetic field, and a changing magnetic field generates an electric field, and the two alternately excite each other and propagate through space.

Key ParameterDescription
Frequency (f)Number of oscillations per second, in Hz. WiFi uses 2.4 GHz = 2.4 billion oscillations per second
Wavelength (λ)Physical length of one complete waveform. λ = c / f ≈ 0.125 m (about 12.5 cm at 2.4 GHz)
AmplitudeSignal strength, affected by distance and obstacles
ModulationThe way data is "encoded" onto a carrier wave (AM/FM/PM)

The higher the electromagnetic wave frequency, the shorter the wavelength, the weaker the penetration capability (greater wall penetration loss), but the larger the amount of data it can carry.

1.2 Why WiFi Uses 2.4 GHz

BandWavelengthCharacteristics
2.4 GHz~12.5 cmStrong wall penetration, but many devices and heavy interference (microwave ovens and Bluetooth also share this band)
5 GHz~6 cmFast, less interference, but weak wall penetration
6 GHz (WiFi 6E)~5 cmNewest band, many channels, but shortest range

The ESP32-S3 only supports 2.4 GHz. A 5G WiFi router must have the 2.4 GHz band enabled at the same time for the ESP32-S3 to connect.


2. How WiFi Works

2.1 Channels

The 2.4 GHz band is divided into 14 channels (China can use 1~13), each channel spaced 5 MHz apart, but the WiFi signal itself occupies 22 MHz of bandwidth.

Channel:   1        6        11
Frequency: 2412MHz  2437MHz  2462MHz
        ████              ████        <- Non-overlapping (1/6/11 recommended)

Channel selection principle: Adjacent routers should select different channels among 1, 6, and 11 to avoid co-channel interference.

2.2 RSSI (Signal Strength)

RSSI (Received Signal Strength Indicator) indicates how strong the signal "heard" by the receiving end is:

RSSI RangeSignal QualityReal-world Experience
> -50 dBmExcellentRouter right next to you
-50 ~ -65 dBmGoodNormal use
-65 ~ -75 dBmFairPossible occasional lag
-75 ~ -85 dBmWeakEdge area, prone to disconnection
< -85 dBmVery weakBasically unusable

dBm is a logarithmic unit: every 3 dB decrease halves the signal power. -50 dBm is 1000 times stronger than -80 dBm.

2.3 Evolution of the 802.11 Protocol Family

StandardYearBandMax RateCommon Name
802.11b19992.4 GHz11 Mbps—
802.11g20032.4 GHz54 Mbps—
802.11n20092.4/5 GHz150 MbpsWiFi 4
802.11ac20135 GHz866 MbpsWiFi 5
802.11ax20192.4/5/6 GHz1200 MbpsWiFi 6

The ESP32-S3 supports 802.11 b/g/n, with a theoretical maximum rate of 150 Mbps (in HT40 mode) and an actual throughput of about 20~50 Mbps.

2.4 WiFi Security Authentication

Authentication ModeEncryption AlgorithmSecurityESP32-S3 Support
OPENNoneInsecure✅
WEPRC4Obsolete (crackable in minutes)✅
WPA-PSKTKIPWeak✅
WPA2-PSKAES-CCMPSecure (recommended)✅
WPA3-PSKSAEMore secure✅
WPA2-EnterpriseAES + RADIUSEnterprise level✅

3. WiFi Operating Modes

3.1 STA Mode (Station)

The ESP32 connects to an existing router like a phone does, obtains an IP address, and then accesses the network.

xxxxxxxxxx
   Internet <- -> [Router/AP] <- -> WiFi <- -> [ESP32-STA]
                                     IP: allocated by DHCP (e.g. 192.168.1.100)

Characteristics:

  • IP is assigned by the router's DHCP (not fixed unless static IP is set)
  • Can access the Internet and the local network
  • The foundation of all subsequent network examples (UDP/TCP/HTTP/MQTT)

3.2 AP Mode (Access Point)

The ESP32 becomes a hotspot itself, and other devices connect to it.

xxxxxxxxxx
                  [ESP32-AP]
                  IP: 192.168.4.1 (fixed)
                  DHCP Server: assigns IPs to clients
                 /    |    \
           [Phone]  [PC]  [Another ESP32]
             .2      .3        .4

Characteristics:

  • IP is fixed at 192.168.4.1, and the ESP32 acts as its own DHCP server
  • Cannot access the Internet (unless NAT forwarding is done)
  • Used for provisioning, direct connection control, and offline LAN communication

3.3 STA + AP Hybrid Mode

The ESP32 acts as both a Station and an Access Point:

xxxxxxxxxx
   Internet <- -> [Router] <- -> [ESP32] <- -> [Phone connects to ESP32 hotspot]
                    WiFi STA      WiFi AP

Typical application: SmartConfig provisioning — the phone connects to the ESP32 hotspot, tells it the router password, then the ESP32 switches to STA mode to connect to the router.

3.4 STA vs AP Comparison

ComparisonSTA ModeAP Mode
RoleClient (connects to others)Hotspot (connected by others)
IP sourceObtained dynamically via DHCPFixed 192.168.4.1
DHCP serviceProvided by routerProvided by ESP32 itself
Max connectionsN/AConfigurable (default 4, max 10)
Network accessCan access the InternetLAN only
Core APIesp_wifi_connect()esp_wifi_start() (no connect needed)
Typical scenarioIoT devices going online, data reportingProvisioning, direct connection control

4. ESP32-S3 WiFi Hardware Features

FeatureParameter
WiFi standardIEEE 802.11 b/g/n
Operating band2.4 GHz
Max transmit power+21 dBm (11b)
Max receive sensitivity-97 dBm (11b)
Supported protocolsWPA/WPA2/WPA3 personal/enterprise
AntennaOn-board ceramic antenna / IPEX external antenna
Operating modesSTA / AP / STA+AP / Sniffer
Channel range1 ~ 14

5. ESP32-S3 WiFi Development Essentials

5.1 Resource Conflict Between WiFi and ADC2

The ESP32-S3 has two ADC units: ADC1 and ADC2. ADC2 shares internal hardware resources with WiFi:

ScenarioADC1ADC2
WiFi offNormalNormal
WiFi onNormalReadings abnormal / unavailable

In development practice, for any project that enables WiFi, analog acquisition must use ADC1 (GPIO 1~9 channel range).

5.2 NVS — WiFi's Storage Dependency

The WiFi driver needs to read the RF calibration parameters stored in NVS (Non-Volatile Storage) during initialization. Whether or not WiFi configuration is saved, nvs_flash_init() is required.

The WiFi driver depends on the RF calibration parameters stored in NVS; the NVS partition must be initialized before startup — if the partition is full or the version is incompatible, erase it and reinitialize.

xxxxxxxxxx
// Initialize the NVS flash; the WiFi driver depends on its RF calibration parameters
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
    // NVS partition full or version mismatch — erase and retry
    ESP_ERROR_CHECK(nvs_flash_erase());
    ret = nvs_flash_init();
}

5.3 Fixed WiFi Initialization Order

The ESP-IDF WiFi initialization order is strictly non-interchangeable; missing a step causes a crash:

WiFi initialization has strict order requirements; all ten steps below are indispensable, and swapping the order will cause startup failure.

xxxxxxxxxx
1. nvs_flash_init()           <- NVS storage
2. esp_netif_init()           <- TCP/IP network stack initialization
3. esp_event_loop_create_default() <- event loop
4. esp_netif_create_default_wifi_sta()  (or _ap())  <- network interface
5. esp_wifi_init(&cfg)        <- WiFi driver
6. Register event callbacks          <- WIFI_EVENT + IP_EVENT
7. esp_wifi_set_mode()        <- STA / AP / APSTA
8. esp_wifi_set_config()      <- SSID + Password
9. esp_wifi_start()           <- start WiFi
10. esp_wifi_connect()         <- initiate connection in STA mode (not needed in AP mode)

If esp_wifi_connect() is called immediately after esp_wifi_start(), it may crash; it is recommended to add vTaskDelay(500ms) to wait for the underlying layer to be ready.

5.4 Antenna

ESP32-S3 development boards usually use an on-board ceramic antenna (the small gray block on the PCB). Some core boards provide an IPEX connector for connecting an external high-gain antenna:

Antenna TypeGainSuitable Scenario
On-board ceramic antenna~2 dBiShort range, general use
IPEX external rod antenna~5 dBiWall penetration, long range

When using an IPEX external antenna, you need to configure the antenna selection GPIO in menuconfig or by calling esp_wifi_set_ant_gpio() in code.

5.5 Strapping Pins

The ESP32-S3's GPIO0, GPIO3, GPIO45, and GPIO46 are strapping pins (they determine the chip's operating mode at startup) and have internal pull-up/pull-down resistors. These pins cannot be used for ADC input, because the internal resistors raise/lower the level so that the reading always stays near VCC or GND.

5.6 WiFi Event-Driven Model

ESP-IDF's WiFi uses an event-driven architecture. WiFi state changes generate events at the underlying layer, and the developer registers callback functions to handle them:

When the underlying WiFi state changes, the corresponding event is triggered, and the callback function dispatches to different handling branches based on the event type.

xxxxxxxxxx
WiFi state change -> WIFI_EVENT / IP_EVENT -> event_handler()
                                    |- WIFI_EVENT_STA_START       -> auto connect
                                    |- WIFI_EVENT_STA_DISCONNECTED -> clear flag + reconnect
                                    |- WIFI_EVENT_SCAN_DONE        -> print AP list
                                    |- WIFI_EVENT_AP_START         -> hotspot created
                                    |- WIFI_EVENT_AP_STACONNECTED  -> a device connected
                                    |- WIFI_EVENT_AP_STADISCONNECTED -> a device disconnected
                                    `- IP_EVENT_STA_GOT_IP       -> set flag + print IP

5.7 EventGroup Synchronization Mechanism

WiFi connection is asynchronous — esp_wifi_connect() returns immediately after being called, and the actual connection result is notified by an event callback. Use the FreeRTOS event group to achieve synchronous waiting:

WiFi connection is an asynchronous operation; the main thread blocks and waits for the connection result through an event group, and the callback sets a bit to notify and unblock it.

​x
// Main thread: block and wait for WiFi connection success
xEventGroupWaitBits(wifi_event_group,   // event group handle
                     WIFI_CONNECTED_BIT, // event bit to wait for
                     // don't clear the bit on exit
                     pdFALSE,
                     // wait for any bit (not all)
                     pdFALSE,
                     timeout);            // blocking timeout in ticks
​
// After getting IP, set the bit and wake up the main thread
xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);

6. WiFi OTA Firmware Upgrade

6.1 What Is OTA

OTA (Over-The-Air) is one of the most important WiFi applications — the device downloads a new firmware via WiFi, writes it to Flash itself, and restarts to switch over, with no USB cable or JTAG programmer needed throughout.

Upgrade MethodOperationApplicable StagePhysical Connection Needed
USB serial flashingUSB cable + idf.py flashDevelopment/debuggingYes
JTAG flashingJTAG debuggerDevelopment/debuggingYes
WiFi OTAHTTP download + partition switchingMass-production productsNo

OTA is the core operation capability of IoT products — deployed devices can be fixed and enhanced without being recalled.

6.2 Flash Partition Layout

OTA requires at least two APP partitions used alternately (A/B switching) to prevent the device from being bricked if power is lost mid-upgrade:

The following is the Flash partition layout in OTA mode; factory stores the factory firmware, ota_0 and ota_1 alternately receive new firmware, and OTA Data records the metadata for the next boot partition.

xxxxxxxxxx
+----------------------------------------------------------+
|                  Flash Layout (OTA mode)                   |
+----------+----------+----------+----------+--------------+
|Bootloader| OTA Data | factory  |  ota_0   |   ota_1      |
|          | (2x4KB)  |  (app)   |  (app)   |   (app)      |
+----------+----------+----------+----------+--------------+
      ↑                     ↑           ↑            ↑ 
    fixed              initial      OTA alternate   (A/B switching)
  • factory: the factory firmware, written during mass-production flashing
  • ota_0 / ota_1: two partitions used alternately. Currently running on ota_0 → OTA writes to ota_1 → restart boots from ota_1 → next OTA writes to ota_0
  • OTA Data: records the "which partition to boot from next" metadata (2 sectors backing each other up)

Why two APP partitions? If power is lost while writing new firmware, the old partition is unaffected, and the device still runs the old version normally after restart. This is OTA's "anti-bricking" mechanism.

6.3 OTA Upgrade Process

xxxxxxxxxx
+--------------+    +--------------+    +--------------+    +--------------+
| 1. Version   | -> | 2. Download  | -> | 3. Write to  | -> | 4. Switch &  |
| check        |    | firmware     |    | partition    |    | reboot       |
| HTTP Range   |    | HTTP GET     |    | esp_ota_write|    | set_boot     |
| get 1KB head |    | complete bin |    | write block  |    | _partition() |
| compare ver  |    |              |    | by block     |    | + restart()  |
+--------------+    +--------------+    +--------------+    +--------------+

Step 1 — Version check: Use an HTTP Range request to download only the first 1024 bytes of the firmware, search for the esp_app_desc_t magic number (0xABCD5432) to locate the version string, and compare it with the local esp_app_get_description()->version. If the server version <= local version, skip the upgrade.

Step 2 — Download firmware: After confirming a new version exists, use HTTP GET to download the complete .bin firmware file.

Step 3 — Write block by block: esp_ota_begin() opens the target partition → loop esp_http_client_read() + esp_ota_write() to write → esp_ota_end() closes and verifies.

Step 4 — Switch boot: esp_ota_set_boot_partition() modifies OTA Data to point to the new partition → esp_restart() restarts.

6.4 Version Extraction — Magic Number Search Method

The layout of the esp_app_desc_t structure in the bin file:

The firmware header contains a magic number identifier and version fields; the version information is located by searching for a fixed byte sequence — the magic number 0xABCD5432 is at offset 0x00, and a 32-byte version string is at offset 0x10.

xxxxxxxxxx
Offset      Content
---------------------------------------------------------
0x00      magic_word = 0xABCD5432          <- magic (little-endian: 32 54 CD AB)
0x04      secure_version
0x08      reserved fields
0x10      version[32]                      <- version string, e.g. "1.0.0"
...

Search process:

  1. HTTP Range bytes=0-1023 to download the first 1KB of the firmware header
  2. Match {0x32, 0x54, 0xCD, 0xAB} byte by byte
  3. Magic offset +0x10 → read the 32-byte version string
  4. Verify that the first character is '0'~'9'

6.5 OTA Core APIs

OTA operations follow a six-step flow of "get partition -> begin write -> write block by block -> end and verify -> set boot partition -> restart and switch", with each step corresponding to a core API.

xxxxxxxxxx
// Get the "next" writable OTA partition (the one other than the currently running partition)
const esp_partition_t *esp_ota_get_next_update_partition(NULL);
​
// Begin OTA write (OTA_SIZE_UNKNOWN = unknown firmware size)
esp_ota_begin(partition, OTA_SIZE_UNKNOWN, &handle);
​
// Write in chunks (4KB max)
esp_ota_write(handle, data, size);
​
// End write (verify + close)
esp_ota_end(handle);
​
// Set the next boot partition (modify OTA Data metadata)
esp_ota_set_boot_partition(partition);
​
// Reboot to new firmware
esp_restart();

6.6 Firmware Server

OTA requires an HTTP file server to host the .bin file. During the testing phase, you can start a simple server on the PC itself:

A single command on the PC starts an HTTP server, and the ESP32 accesses this address via WiFi to download the firmware.

xxxxxxxxxx
# Start HTTP server with Python 3 (port 8080, root = current directory)
python -m http.server 8080
​
# On Windows, ensure the firewall allows port 8080

On the ESP32 side, OTA_URL points to http://<PC_IP>:8080/WiFi_OTA.bin.

6.7 OTA Notes

PointDescription
The partition table must contain OTA partitionsmenuconfig -> Partition Table -> "Factory app, two OTA definitions"
Firmware size limitota_0/ota_1 each occupy half of the Flash minus factory; exceeding it causes esp_ota_write to fail
Network stabilityIf WiFi disconnects mid-download, esp_ota_abort() rolls back and the device still runs the old version
Version number formatNumbers and dots only (1.0.0), no v prefix
SecurityProduction environments should use HTTPS + certificate verification + firmware signing to prevent man-in-the-middle attacks
RollbackESP-IDF supports automatic rollback — if the new firmware restarts N times consecutively, it automatically switches back to the old version

For the complete code implementation and operating steps, see (5.Network Protocols and Wireless Communication -> 12.WIFI-OTA Upgrade -> WIFI-OTA Upgrade).


7. WiFi Common Problem Troubleshooting

SymptomCauseSolution
Always prints "Disconnected, reconnecting..."Wrong SSID or passwordCheck the WIFI_SSID and WIFI_PASS macros
Fails to connect to 5G WiFiESP32-S3 only supports 2.4GMake sure the router's 2.4G band is enabled
Got IP but cannot ping the InternetRouter has no Internet connection / DNS issuePing the router IP first to confirm the LAN is reachable
esp_wifi_connect() returns an errorWiFi not fully initializedEnsure vTaskDelay(500ms) is added after esp_wifi_start()
WIFI_EVENT_STA_DISCONNECTED triggers frequentlyWeak signal or congested router channelGet closer to the router / change the WiFi channel
Compile error: nvs_flash.h not foundNVS not initializedAdd nvs_flash_init() at the beginning of app_main()
Phone cannot find the hotspot in AP modeChannel occupied / not started properlyCheck the log to confirm WiFi AP started; try changing AP_CHANNEL
AP mode prompts "wrong password" when connectingPassword shorter than 8 charactersWPA2 requires a password of >= 8 characters

Common Network Communication Protocols


Importance: The TCP/IP protocol stack is the underlying foundation of all network communication on the ESP32-S3 — whether you use WiFi, Ethernet, HTTP, MQTT, or OTA upgrade, data is ultimately transmitted over the network through the TCP/IP protocol stack. Understanding the layered model, IP addressing, the port mechanism, the Socket API, and the core differences between TCP and UDP is a prerequisite for troubleshooting network problems, optimizing communication performance, and designing reliable IoT applications. This chapter does not involve specific code flashing, but instead establishes a theoretical framework for network communication — all API calls, parameter configuration, and exception troubleshooting in the subsequent network examples (UDP/TCP/HTTP/MQTT) are based on the knowledge in this chapter.


1. The TCP/IP Protocol Stack

1.1 The Layered Model

The essence of network communication is layer-by-layer encapsulation and peer-to-peer communication:

xxxxxxxxxx
+-------------------------------------------------------------+
|               Application Layer                              |  HTTP / MQTT / DNS / OTA
|  http://example.com/api  ->  "Hello ESP32"                   |
+-------------------------------------------------------------+
|               Transport Layer                                |  TCP / UDP
|  Port numbers (80/8080/1883) + reliable/unreliable transport  |
+-------------------------------------------------------------+
|               Internet Layer                                 |  IP
|  IP address (192.168.1.100) + routing + fragmentation         |
+-------------------------------------------------------------+
|               Link Layer                                     |  WiFi / Ethernet
|  MAC address (AA:BB:CC:DD:EE:FF) + channel access            |
+-------------------------------------------------------------+

1.2 Data Encapsulation Process

When sending data, each layer adds its own header, like Russian nesting dolls:

xxxxxxxxxx
Application layer:  [ HTTP GET /index.html ]
                        | add TCP header
Transport layer:  [ TCP header | src_port=12345 dst_port=80 | HTTP GET ... ]
                        | add IP header
Internet layer:  [ IP header | src=192.168.1.100 dst=93.184.216.34 | TCP header | HTTP GET ... ]
                        | add WiFi frame header
Link layer:  [ WiFi frame header | src=AA:BB:CC dst=DD:EE:FF | IP header | TCP header | HTTP GET ... | FCS checksum ]

The receiving end de-encapsulates layer by layer until the application layer gets the original data.

1.3 Key Protocol Comparison

ProtocolLayerReliabilityConnectionHeader OverheadTypical Use
IPInternet layerUnreliableConnectionless20BAddressing, routing
ICMPInternet layerUnreliableConnectionless8BPing, error reporting
TCPTransport layerReliableConnection-oriented20BWeb, files, MQTT
UDPTransport layerUnreliableConnectionless8BDNS, video streams, sensors
ARPLink layer——28BIP->MAC address resolution
DHCPApplication layer———Automatic IP acquisition

2. IP Address

The IP address is the "door number" of network communication — the ESP32 can only be accessed by other devices on the LAN after obtaining an IP, and it is a prerequisite for all subsequent Socket communication, HTTP requests, and MQTT connections.

2.1 IPv4 Basics

An IPv4 address consists of 32 bits, written as 4 decimal segments (each 0~255):

xxxxxxxxxx
192     .   168     .   1       .   100
11000000  10101000  00000001  01100100     <- 32-bit binary
+------------------------+  +-------+ 
           network part            host part
      (the subnet mask determines the boundary)

2.2 Subnet Mask

The subnet mask determines which part of an IP address is the "network number" and which is the "host number":

Subnet MaskCIDRUsable IPsCommon Scenario
255.255.255.0/24254Home router
255.255.0.0/1665534Large enterprise
xxxxxxxxxx
IP:      192.168.  1.100
Mask:   255.255.255.  0
        ==========   ===
         network     host part (0~255, where 0=network number, 255=broadcast)

All devices in the same network have the same "network part" and different "host parts".

2.3 Public IP vs Private IP

RangeTypeDescription
10.0.0.0 ~ 10.255.255.255Private Class ALarge enterprise internal
172.16.0.0 ~ 172.31.255.255Private Class BMedium enterprise internal
192.168.0.0 ~ 192.168.255.255Private Class C (home Ethernet)Most common — home routers
OthersPublic IPUnique on the Internet, must be purchased

Private IPs cannot be directly accessed from the Internet — the router maps private IPs to public IPs through NAT (Network Address Translation).

2.4 Special IP Addresses

IPMeaningUse
127.0.0.1Local loopback (localhost)Accessing yourself
0.0.0.0Any addressBinding to all network interfaces
255.255.255.255Broadcast addressSending to all devices on the LAN
192.168.1.1Usually the router gatewayEntry to the admin page

3. Ports

The port is the key to "multiple services on one device" — the ESP32 can simultaneously run an HTTP server (80), an MQTT client (1883), and a TCP data channel (8080), with each service bound to a different port without interfering. Firewall and NAT configuration also depends on port numbers.

3.1 The Concept of Ports

The IP address locates the device, and the port locates the program on the device.

xxxxxxxxxx
                     ESP32-S3 (192.168.1.100)
                    +--------------------------------+
                    |  Port 80   -> HTTP Server      |
   network data ->  |  Port 1883 -> MQTT Client      |
                    |  Port 8080 -> TCP Server       |
                    |  Port 12345 -> system dynamic  |
                    +--------------------------------+

Ports are 16-bit numbers (0~65535):

RangeTypeDescription
0 ~ 1023Well-known portsHTTP=80, HTTPS=443, MQTT=1883, DNS=53
1024 ~ 49151Registered portsCustom services (e.g. 8080)
49152 ~ 65535Dynamic portsTemporary use by clients

3.2 Client Port vs Server Port

xxxxxxxxxx
Client (browser/ESP32)                     Server
----------------------------           -----------------
socket()                                   socket()
(system auto-assigns temporary               bind(80)           <- must use a fixed port,
 port, e.g. 52341)                                          otherwise the client
                                                              won't know which port to connect to
connect(93.184.216.34:80) ------ >  listen(80) + accept()
                                    received connection: client IP:52341 <-> server IP:80
send() ------------------------- >  recv() -> process -> send()
recv() <--------------------------  (reply)

The server must bind() a fixed port, otherwise the client won't know where to connect; the client port is auto-assigned by the OS (used and discarded).


4. Socket Programming Basics

Socket is the core API layer of ESP-IDF network programming — whether it is custom TCP/UDP communication, an HTTP client, or an MQTT client, data is sent and received through Sockets underneath. Mastering Socket data structures, byte order conversion, and creation methods is the basis for reading and writing all network code.

4.1 What Is a Socket

Socket is the network programming interface provided by the operating system — developers send and receive data through Sockets without worrying about details such as underlying WiFi frames, IP fragmentation, and TCP retransmission.

xxxxxxxxxx
Application code                    OS kernel
---------                         -------------
send(sock, "Hello", 5)
    |                              +-------------+
    +------------------------------>   TCP stack  | -> segment -> add TCP header
                                   +-------------+
                                   |   IP stack   | -> fragment -> add IP header -> route
                                   +-------------+
                                   |  WiFi driver | -> add WiFi frame -> DMA -> antenna transmit
                                   +-------------+

4.2 Key Data Structures

The two most core address structures in Socket programming — sockaddr is the generic type and sockaddr_in is the IPv4-specific type; all Socket APIs use the latter via a cast.

xxxxxxxxxx
// Generic socket address (IPv4/IPv6)
struct sockaddr {
    // Address family: AF_INET (IPv4) or AF_INET6 (IPv6)
    sa_family_t sa_family;
    char        sa_data[14];  // Protocol address (IP + port)
};
struct sockaddr_in {
    sa_family_t    sin_family; // Address family: IPv4
    // Port number (network byte order)
    uint16_t       sin_port;
    struct in_addr sin_addr;   // IP address
};
struct sockaddr_in server_addr;
bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

4.3 Network Byte Order

Network byte order = Big-Endian, meaning the high-order byte is stored at the low address. The ESP32 CPU is little-endian, opposite to network order, so conversion is required:

xxxxxxxxxx
Number 0x12345678 (32-bit)
​
Big-Endian (network order):
low address -> high address
  12 | 34 | 56 | 78     <- high byte first
​
Little-Endian (ESP32 host order):
low address -> high address
  78 | 56 | 34 | 12     <- low byte first
FunctionMeaningUse
htons(n)Host TO Network Short (16-bit)Port number conversion
htonl(n)Host TO Network Long (32-bit)IP address conversion (rarely used)
ntohs(n)Network TO Host ShortRestore after receiving
ntohl(n)Network TO Host LongRestore after receiving
inet_pton()String -> binary IP (automatic network order)"192.168.1.1" -> 0x0101A8C0

Both ports and IP addresses need to be converted to network byte order — htons() converts the port, and inet_pton() converts the IP string to network-order binary.

xxxxxxxxxx
// Correct: use conversion functions
// Convert to network byte order
addr.sin_port = htons(8080);
// String -> binary (network order)
inet_pton(AF_INET, "192.168.1.100", &addr.sin_addr);
​
// Wrong: direct assignment
// CPU is little-endian, network sees 0x901F
addr.sin_port = 8080;

4.4 Socket Creation Types

socket() distinguishes TCP (stream) from UDP (datagram) via the type parameter — this is the first step of all subsequent Socket operations and determines the communication mode.

xxxxxxxxxx
int fd = socket(domain, type, protocol);  // General form
int tcp_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int udp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
ParameterTCPUDP
domainAF_INET (IPv4)AF_INET (IPv4)
typeSOCK_STREAM (stream)SOCK_DGRAM (datagram)
BehaviorConnection-oriented, reliable, byte streamConnectionless, unreliable, preserves message boundaries

5. TCP in Depth

TCP is the most commonly used reliable transport protocol for IoT devices — firmware OTA upgrades cannot lose a single byte, MQTT messages must be delivered reliably, and HTTP pages must load completely. All these scenarios rely on TCP's acknowledgment and timeout retransmission mechanisms. Understanding the three-way handshake, four-way termination, and the recv() return value is the basis for running a stable TCP service.

5.1 Three-Way Handshake

xxxxxxxxxx
     Client (ESP32)                         Server (PC)
    ---------------                         -------------
    socket()                            socket() + bind() + listen()
    |                                     |
    |----   SYN (seq=x, no data) --------->|  connect() initiates
    |                                     |  server replies SYN+ACK
    |<-- SYN+ACK (seq=y, ack=x+1)   ------|
    |                                     |
    |----  ACK (ack=y+1) ---------------->|  handshake complete
    |                                     |
    =========== ESTABLISHED ==============  (bidirectional communication ready)
  • SYN: request to establish a connection
  • SYN+ACK: agree + request (the server also confirms its own direction)
  • ACK: confirmation (officially established)

The essence of the three-way handshake is that both sides confirm the other's send/receive capability is normal.

5.2 Four-Way Termination

xxxxxxxxxx
     Client                                  Server
    ---------                               ---------
    close() or shutdown()
    |---- FIN (seq=u) ------------------>|  Client: "I have no more data"
    |<--- ACK (ack=u+1)  ----------------|  Server: "received"
    |                                    |  (server may still have data to send)
    |<--- FIN (seq=v)  ------------------|  Server: "I have no more data either"
    |---- ACK (ack=v+1) ---------------->|  Client: "received"
    |                                    |
    ======== connection closed ============

TCP is full-duplex — each direction closes independently. close() closes both directions; shutdown(fd, SHUT_WR) closes only the write direction (you can still receive).

5.3 How Reliable Transmission Is Implemented

TCP reliability comes from three mechanisms:

MechanismPrinciple
Acknowledgment (ACK)Reply with an ACK after receiving data; the sender retransmits if no ACK is received
Sequence number (SEQ)One number per byte; the receiver sorts and reassembles by sequence number
Timeout retransmission (RTO)Start a timer after sending; retransmit if no ACK is received before timeout

5.4 The Three Return Cases of recv()

Return ValueMeaningHandling
> 0Received n bytes of dataProcess normally
= 0The peer closed the connection normally (sent FIN)close() and break
< 0No data available (MSG_DONTWAIT) or an errorCheck errno

The three return values of recv() correspond to three handling branches — this is the standard template for TCP receive logic.

xxxxxxxxxx
int ret = recv(sock_fd, buf, len, 0);
if (ret > 0)     { /* Data received, process normally */ }
else if (ret == 0) { /* Peer closed, break and close */ }
else             { /* No data (non-blocking), or real error */ }

5.5 Standard TCP Server Flow

xxxxxxxxxx
socket() -> bind() -> listen() -> while(1) {
    client_fd = accept() -> while(1) {
        recv() / send()    <- communicate with a single client
    } -> close(client_fd)   <- client disconnected, back to accept
}

6. UDP in Depth

UDP's low overhead and low latency make it the first choice for scenarios such as high-frequency sensor data reporting, real-time audio/video streams, and DNS queries. In IoT, when "speed takes priority over reliability" — such as temperature and humidity collection hundreds of times per second, or device discovery broadcasts — UDP is more suitable than TCP.

6.1 The Meaning of Connectionless

UDP does not handshake, establish connections, or guarantee delivery — datagrams are like throwing a message in a bottle:

xxxxxxxxxx
      Client (ESP32)                               Server (PC)
     ---------------                             -------------
     socket(SOCK_DGRAM)                        socket(SOCK_DGRAM) + bind(8080)
     |                                          |
     |-- sendto("Hello", 192.168.1.183:8080) -->|  direct send
     |                                          |  (if it arrives, it arrives; if not, forget it)
     |<-- sendto("Reply", 192.168.1.100:52341) --|  reply

6.2 UDP Suitable Scenarios

✅ Suitable for UDP❌ Not suitable for UDP
Video/audio real-time streams (occasional glitches OK)File transfer (not a single byte can be lost)
DNS queries (small request volume, timeout-retry is fine)Web browsing (HTML must be complete)
High-frequency sensor data (losing a few frames is fine)Firmware OTA upgrades (firmware must be complete)
Broadcast/multicast messagesFinancial transactions (packet loss = money loss)

6.3 UDP vs TCP API Comparison

Comparison of the TCP and UDP API call flows — TCP needs listen() + accept() to establish a connection and then communicate via the file descriptor; UDP directly uses sendto() / recvfrom() carrying the target address.

xxxxxxxxxx
// ===== TCP Server =====                        // ===== UDP Server =====
socket(AF_INET, SOCK_STREAM, 0)            socket(AF_INET, SOCK_DGRAM, 0)
bind(fd, addr, len)                        bind(fd, addr, len)
listen(fd, 5)                              // No listen
// No accept, direct recvfrom
client_fd = accept(fd, ...)
recv(client_fd, buf, len, 0)               recvfrom(fd, buf, len, 0, &addr, &len)
send(client_fd, buf, len, 0)               sendto(fd, buf, len, 0, &addr, len)
​
// ===== TCP Client =====                        // ===== UDP Client =====
socket(AF_INET, SOCK_STREAM, 0)            socket(AF_INET, SOCK_DGRAM, 0)
connect(fd, &addr, len)                    // No connect
send(fd, buf, len, 0)                      sendto(fd, buf, len, 0, &addr, len)
recv(fd, buf, len, 0)                      recvfrom(fd, buf, len, 0, &addr, &len)

6.4 Non-Blocking Receive (MSG_DONTWAIT)

The MSG_DONTWAIT flag makes recvfrom() / recv() non-blocking — when there is no data, it immediately returns -1 (errno=EAGAIN) without blocking the task, which is suitable for high-frequency polling scenarios (such as a low-latency receive loop every 10 ms).

xxxxxxxxxx
int recv_len = recvfrom(sock_fd, recv_buf, sizeof(recv_buf)-1,
                         MSG_DONTWAIT,       // Non-blocking flag
                         (struct sockaddr *)&from_addr, &len);
if (recv_len > 0) {
    // Data received, process it
}

7. HTTP Protocol Basics

HTTP is the standard protocol for IoT devices to interact with cloud REST APIs — devices use GET to fetch configuration, POST to report sensor data, and Range requests to implement OTA firmware chunk downloads. Understanding the request/response format and status codes is the prerequisite for calling Web APIs.

7.1 Request Format

xxxxxxxxxx
GET /index.html HTTP/1.1\r\n          <- Request line: method + URI + version
Host: example.com\r\n                 <- Request headers: key-value pairs
User-Agent: ESP32\r\n
Accept: */*\r\n
\r\n                                  <- blank line = end of headers
                                      <- Request body (empty for GET, content for POST)

7.2 Response Format

xxxxxxxxxx
HTTP/1.1 200 OK\r\n                    <- Status line: version + status code + reason phrase
Content-Type: text/html\r\n            <- Response headers
Content-Length: 125\r\n
Connection: close\r\n
\r\n                                   <- blank line = end of headers
<html>...response body...</html>        <- Response body

7.3 Common Status Codes

Status CodeMeaningDescription
200OKRequest succeeded
206Partial ContentRange request returns partial content (OTA firmware header download)
301Moved PermanentlyPermanent redirect
302FoundTemporary redirect
400Bad RequestMalformed request
404Not FoundResource does not exist
500Internal Server ErrorInternal server error

7.4 Common HTTP Methods

MethodSemanticsRequest BodyTypical Use
GETFetch a resourceNoneQuerying data, fetching web pages
POSTSubmit dataYesSubmitting forms, uploading sensor data
PUTReplace a resourceYesUpdating configuration
DELETEDelete a resourceNoneDeleting records

8. MQTT Protocol Basics

8.1 Why IoT Uses MQTT Instead of HTTP

ComparisonMQTTHTTP
Communication modePublish/subscribe (Broker relay)Request/response (direct)
Message pushNative support, subscribe to get pushedNeeds client polling (or WebSocket)
Minimum protocol header2 bytesHundreds of bytes
Connection keep-aliveKeep Alive heartbeatStateless (each request is an independent connection)
One-to-manyNaturally supported (many subscribe to the same Topic)Needs server polling + push logic

8.2 Publish/Subscribe Model

xxxxxxxxxx
                  +-------------+
                  | MQTT Broker |      <- core: all messages routed by the Broker
                  +-------+-----+
     subscribe    |       |              subscribe
sensor/temp  +---+         +---+   sensor/alert
             |                 |
        +----+-----+     +----+-----+
        | temp sensor |     | monitor center |
        | publish()  |     | auto receives |
        |sensor/temp|     | temp data   |
        +-----------+     +-----------+

Three roles:

RoleDescriptionExample
PublisherSends messages to a specific TopicESP32 reports temperature
SubscriberSubscribes to a Topic and automatically receives messagesPhone App subscribes to sensor data
BrokerRelays all messages, manages Topic subscription relationshipsEMQX, Mosquitto

8.3 Topic Wildcards

WildcardSemanticsExample
+Matches one levelhome/+/light -> home/bedroom/light
#Matches multiple levelshome/# -> home/bedroom/light/status

8.4 The Three QoS Levels

QoSSemanticsMechanism
0At most once (fire and forget)No retry, no acknowledgment
1At least once (may duplicate)Send -> wait for PUBACK -> resend on timeout
2Exactly once (no duplicates)PUBREC -> PUBREL -> PUBCOMP four-step handshake

9. ESP-IDF Network API Selection Guide

When developing network applications, ESP-IDF provides APIs from the bottom to the top; choose based on your needs:

xxxxxxxxxx
High level (simple, well-encapsulated features)
  |  esp_http_client / esp_http_server    <- HTTP request/server
  |  mqtt_client                          <- MQTT client
  |  esp_ota                              <- OTA upgrade
  |
  |  lwip/sockets (BSD Socket API)        <- raw TCP/UDP communication
  |    socket / bind / listen / accept / connect
  |    send / recv / sendto / recvfrom
  |
Low level (flexible, manual handling of details needed)
  |  esp_wifi                             <- WiFi connect/scan/config
  |  esp_netif                            <- network interface management
  |  esp_event                            <- event-driven framework
If you want to...Use this API
Connect WiFiesp_wifi + esp_netif
Custom TCP/UDP communicationlwip/sockets (BSD Socket)
Access web pages / REST APIsesp_http_client
Set up a web serveresp_http_server
IoT sensor reporting / remote controlmqtt_client
WiFi remote firmware upgradeesp_ota + esp_http_client
Ping a remote hostlwip/ping.h or esp_ping

10. Common Debugging Methods

Network troubleshooting uses a layered localization strategy — confirm level by level from the bottom up: WiFi connection -> IP acquisition -> LAN reachability -> port listening -> application-layer protocol. Skipping levels can easily lead you astray.

10.1 Troubleshooting Steps

xxxxxxxxxx
Problem: ESP32 cannot communicate
​
1. First check the serial log for "Got IP: xxx.xxx.xxx.xxx"
   |-- Not there -> WiFi not connected -> check SSID/password/band
   `-- There -> WiFi is fine, continue troubleshooting
​
2. Ping test
   |-- ping ESP32 IP     -> verify whether the IP layer works
   |-- ping router IP    -> verify LAN reachability
   `-- ping 8.8.8.8      -> verify Internet reachability (DNS-independent, pure IP)
​
3. Port test
   |-- On the PC, use netstat -an | findstr 8080 to check whether the port is listening
   `-- Use a network debugging assistant to send data to the ESP32 IP:PORT
​
4. Firewall check
   `-- The Windows firewall may block non-standard ports such as 8080

10.2 Common Debugging Commands

Common network debugging commands for the PC and ESP32 sides — first confirm network reachability from the PC side, then confirm the running status from the ESP32 logs.

xxxxxxxxxx
# PC side (Windows PowerShell)
ipconfig                    # Check local IP
ping 192.168.1.100          # Ping ESP32
netstat -an | findstr 8080  # Check port 8080 status
curl http://192.168.1.100/  # Test HTTP server
​
# ESP32 side (add in code)
ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&ip));  // Print obtained IP
// Check free memory
ESP_LOGI(TAG, "Free heap: %lu", esp_get_free_heap_size());

11. Common Network Problems

SymptomCauseSolution
connect() returns -1Server not started or wrong IPConfirm the PC Server is listening and the IP and port are correct
bind() failsPort occupiedUse another port / wait 2 minutes (TIME_WAIT timeout)
recv() returns 0The peer actively closed the connectionNormal disconnect; break then close()
Data received by recv() is "stuck" togetherTCP is a byte stream with no message boundariesUse an application-layer custom frame header + length or a delimiter protocol
send() fails repeatedlyPeer closed / network interruptedThe TCP connection is broken; reconnect with connect()
Garbled Chinese text when sendingInconsistent terminal encodingCheck the encoding settings of the serial assistant and network assistant (UTF-8)
PC cannot receive ESP32 dataESP32 IP changed / firewall blockingCheck the ESP32's actual IP on the serial port; allow the corresponding port in the PC firewall
HTTP client HTTP request errorURL unreachable or DNS resolution failedMake sure the ESP32 can access the Internet; or use an IP instead of a domain name
MQTT MQTT_EVENT_CONNECTED not triggeredWrong Broker address or no Internet on WiFiping broker.emqx.io to test Internet reachability
Print Storage
WIFI STA Mode

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文