yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
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.4GHz2. How WiFi Works2.1 Channels2.2 RSSI (Signal Strength)2.3 802.11 Protocol Evolution2.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 Specifications5. ESP32-S3 WiFi Development Key Points5.1 WiFi and ADC2 Resource Conflict5.2 NVS - WiFi Storage Dependency5.3 WiFi Initialization Fixed Sequence5.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 Flow6.4 Version Extraction — Magic Number Search Method6.5 OTA Core APIs6.6 Firmware Server6.7 OTA Precautions7. WiFi Common TroubleshootingCommon Network Communication Protocols1. TCP/IP Protocol Stack1.1 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. Port3.1 Concept of Port3.2 Client Port vs Server Port4. Socket Programming Basics4.1 What is Socket4.2 Key Data Structures4.3 Network Byte Order4.4 Socket Creation Types5. TCP In-Depth5.1 Three-Way Handshake5.2 Four-Way Wavehand5.3 How Reliable Transmission is Achieved5.4 Three Cases of recv() Return Value5.5 TCP Server Standard Flow6. UDP In-Depth6.1 What "Connectionless" Means6.2 UDP Applicable 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 QoS Three Levels9. ESP-IDF Network API Selection Guide10. Common Debug Methods10.1 Troubleshooting Steps10.2 Common Debug Commands11. Common Network Problems


1. Electromagnetic Waves and Wireless Communication

1.1 What are Electromagnetic Waves

The essence of WiFi is electromagnetic waves - changing electric fields generate magnetic fields, changing magnetic fields generate electric fields, and the two alternate to propagate through space.

Key ParameterDescription
Frequency (f)Oscillations per second, unit Hz. WiFi uses 2.4 GHz = 2.4 billion oscillations per second
Wavelength (λ)Physical length of one complete wave. λ = c / f ≈ 0.125m (~12.5cm at 2.4GHz)
AmplitudeSignal strength, affected by distance and obstacles
ModulationMethod of "encoding" data onto a carrier wave (amplitude/frequency/phase modulation)

The higher the electromagnetic wave frequency, the shorter the wavelength, the weaker the penetration ability (greater wall penetration loss), but the more data it can carry.

1.2 Why WiFi Uses 2.4GHz

Frequency BandWavelengthCharacteristics
2.4 GHz~12.5 cmStrong wall penetration, but crowded spectrum with more interference (microwave ovens, Bluetooth operate on this band)
5 GHz~6 cmFaster speed, less interference, but weaker wall penetration
6 GHz (WiFi 6E)~5 cmLatest band, extremely many channels, but shortest range

ESP32-S3 only supports 2.4GHz. 5G WiFi routers need to enable 2.4G band as well for ESP32-S3 to connect.


2. How WiFi Works

2.1 Channels

The 2.4GHz band is divided into 14 channels (China uses 1~13), with each channel spaced 5MHz apart, but WiFi signals themselves occupy 22MHz bandwidth.

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

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

2.2 RSSI (Signal Strength)

RSSI (Received Signal Strength Indicator) indicates how strong the signal the receiver "hears":

RSSI RangeSignal QualityUser Experience
> -50 dBmExcellentRouter is right next to you
-50 ~ -65 dBmGoodNormal use
-65 ~ -75 dBmFairPossible occasional stuttering
-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 802.11 Protocol Evolution

StandardYearFrequency BandMax 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

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

2.4 WiFi Security Authentication

Authentication ModeEncryption AlgorithmSecurityESP32-S3 Support
OPENNoneInsecure✅
WEPRC4Deprecated (crackable in minutes)✅
WPA-PSKTKIPWeak✅
WPA2-PSKAES-CCMPSecure (Recommended)✅
WPA3-PSKSAEMore Secure✅
WPA2-EnterpriseAES + RADIUSEnterprise-grade✅

3. WiFi Operating Modes

3.1 STA Mode (Station)

ESP32 connects to an existing router like a phone, getting an IP address to access the internet.

xxxxxxxxxx
   Internet ←→ [Router/AP] ←→ WiFi ←→ [ESP32-STA]
                                      IP: DHCP dynamically assigned (e.g., 192.168.1.100)

Characteristics:

  • IP is assigned by router DHCP (not fixed, unless static IP is set)

  • Can access internet and LAN

  • Foundation for all subsequent network examples (UDP/TCP/HTTP/MQTT)

3.2 AP Mode (Access Point)

ESP32 becomes its own hotspot, other devices connect to it.

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

Characteristics:

  • IP is fixed at 192.168.4.1, ESP32 acts as DHCP server itself

  • Cannot access internet (unless doing NAT forwarding)

  • Used for configuration provisioning, direct connection control, offline LAN communication

3.3 STA + AP Hybrid Mode

ESP32 operates as both Station and Access Point simultaneously:

xxxxxxxxxx
   Internet ←→ [Router] ←→ [ESP32] ←→ [Phone connected to ESP32 hotspot]
                 WiFi STA    WiFi AP

Typical application: SmartConfig Provisioning - Phone connects to ESP32 hotspot → tells it the router password → ESP32 switches to STA mode to connect to router.

3.4 STA vs AP Comparison

ComparisonSTA ModeAP Mode
RoleClient (connects to others)Hotspot (others connect to it)
IP SourceDHCP dynamic assignmentFixed 192.168.4.1
DHCP ServiceProvided by routerProvided by ESP32 itself
Max ConnectionsN/AConfigurable (default 4, max 10)
Network CapabilityCan access internetLAN only
Core APIesp_wifi_connect()esp_wifi_start() (no connect needed)
Typical ScenarioIoT device internet access, data reportingConfiguration provisioning, direct control

4. ESP32-S3 WiFi Hardware Specifications

FeatureParameter
WiFi StandardIEEE 802.11 b/g/n
Operating Frequency2.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 Key Points

5.1 WiFi and ADC2 Resource Conflict

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

ScenarioADC1ADC2
WiFi OffNormalNormal
WiFi OnNormalAbnormal readings / unavailable

In development practice, any project enabling WiFi must use ADC1 (GPIO 1~9 channel range) for analog采集.

5.2 NVS - WiFi Storage Dependency

WiFi driver needs to read RF calibration parameters stored in NVS (Non-Volatile Storage) during initialization. Regardless of whether WiFi configuration is saved, nvs_flash_init() is required.

WiFi driver depends on RF calibration parameters stored in NVS; NVS partition must be initialized before WiFi starts - if partition is full or version incompatible, just erase and reinitialize.

xxxxxxxxxx
// Initialize NVS flash, WiFi driver depends on 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 WiFi Initialization Fixed Sequence

ESP-IDF WiFi initialization sequence is strictly fixed - missing any step causes crash:

WiFi initialization has strict sequence requirements, the following ten steps are all essential, reversed order leads to startup failure.

xxxxxxxxxx
① nvs_flash_init()           ← NVS storage
② esp_netif_init()           ← TCP/IP network stack initialization
③ esp_event_loop_create_default() ← Event loop
④ esp_netif_create_default_wifi_sta()  (or _ap())  ← Network interface
⑤ esp_wifi_init(&cfg)        ← WiFi driver
⑥ Register event callbacks       ← WIFI_EVENT + IP_EVENT
⑦ esp_wifi_set_mode()        ← STA / AP / APSTA
⑧ esp_wifi_set_config()      ← SSID + Password
⑨ esp_wifi_start()           ← Start WiFi
⑩ esp_wifi_connect()         ← STA mode initiates connection (AP mode doesn't need this)

If esp_wifi_connect() is called immediately after esp_wifi_start(), it may cause crash, it is recommended to add vTaskDelay(500ms) to wait for low-level readiness.

5.4 Antenna

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

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

When using IPEX external antenna, set antenna selection GPIO via menuconfig or call esp_wifi_set_ant_gpio() in code.

5.5 Strapping Pins

ESP32-S3's GPIO0, GPIO3, GPIO45, GPIO46 are Strapping pins (determine chip operating mode at startup), with internal pull-up/pull-down resistors. These pins cannot be used for ADC input because internal resistors will raise/lower the voltage level, making readings always close to VCC or GND.

5.6 WiFi Event-Driven Model

ESP-IDF WiFi uses event-driven (Event-Driven) architecture. WiFi state changes generate events from the underlying layer, developers register callback functions to handle:

WiFi underlying state changes trigger corresponding events, callback function dispatches to different handling branches based on 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  → Device connected
                                    ├─ WIFI_EVENT_AP_STADISCONNECTED → Device disconnected
                                    └─ IP_EVENT_STA_GOT_IP       → Set flag + Print IP

5.7 EventGroup Synchronization Mechanism

WiFi connection is asynchronous - after esp_wifi_connect() call returns immediately, actual connection result is notified via event callback. Using FreeRTOS Event Group to implement synchronized waiting:

WiFi connection is an asynchronous operation, main thread blocks waiting for connection result via event group, callback sets bit to unblock.

​x
// Main thread: block waiting 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);           // Block timeout

// Got IP, set bit, wake 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 - device downloads new firmware via WiFi, writes to Flash and restarts to switch, all without USB cable or JTAG programmer.

Upgrade MethodOperationApplicable StageRequires Physical Connection
USB Serial FlashUSB cable + idf.py flashDevelopment/DebuggingYes
JTAG FlashJTAG debuggerDevelopment/DebuggingYes
WiFi OTAHTTP Download + Partition SwitchMass ProductionNo

OTA is a core operational capability for IoT products - deployed devices can be repaired without recall.

6.2 Flash Partition Layout

OTA requires at least two APP partitions alternating (A/B switching) to prevent brick from power failure during upgrade:

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

xxxxxxxxxx
┌──────────────────────────────────────────────────────────┐
│                     Flash Layout (OTA Mode)                  │
├──────────┬──────────┬──────────┬──────────┬──────────────┤
│Bootloader│ OTA Data │ factory  │  ota_0   │   ota_1      │
│          │ (2×4KB)  │  (app)   │  (app)   │   (app)      │
└──────────┴──────────┴──────────┴──────────┴──────────────┘
     ↑                      ↑           ↑           ↑
    Fixed                First factory   OTA alternating partitions (A/B switching)
  • factory: Factory firmware, written during mass production

  • ota_0 / ota_1: Two partitions alternating use. Currently running on ota_0 → OTA writes to ota_1 → Restart boots from ota_1 → Next OTA writes to ota_0

  • OTA Data: Records metadata of "which partition to boot from next" (2 sectors backup each other)

Why two APP partitions are needed? If power fails while writing new firmware, old partition is unaffected, device restarts and still runs old version normally. This is OTA's "anti-brick" mechanism.

6.3 OTA Upgrade Flow

xxxxxxxxxx
┌──────────────┐    ┌──────────────┐    ┌──────────────┐    ┌──────────────┐
│ 1. Version Check │ → │ 2. Download Firmware │ → │ 3. Write Partition │ → │ 4. Switch Reboot   │
│ HTTP Range   │    │ HTTP GET     │    │ esp_ota_write│    │ set_boot     │
│ Get firmware header 1KB   │    │ Full bin file │    │ Write in chunks│    │ _partition() │
│ Compare version    │    │              │    │              │    │ + restart()  │
└──────────────┘    └──────────────┘    └──────────────┘    └──────────────┘

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

Step 2 — Download Firmware: After confirming new version available, HTTP GET downloads the full .bin firmware file.

Step 3 — Write in Chunks: esp_ota_begin() opens target partition → loop esp_http_client_read() + esp_ota_write() → esp_ota_end() closes and verifies.

Step 4 — Switch Boot: esp_ota_set_boot_partition() modifies OTA Data pointing to new partition → esp_restart() reboots.

6.4 Version Extraction — Magic Number Search Method

esp_app_desc_t structure layout in bin file:

Firmware header contains magic number identifier and version number field, locate version information by searching fixed byte sequence - magic number 0xABCD5432 at offset 0x00, 32-byte version string at offset 0x10.

xxxxxxxxxx
Offset      Content
────────────────────────────────────────
0x00      magic_word = 0xABCD5432          ← Magic number (little-endian: 32 54 CD AB)
0x04      secure_version
0x08      Reserved field
0x10      version[32]                      ← Version string, e.g., "1.0.0"
...

Search process:

  1. HTTP Range bytes=0-1023 downloads firmware header 1KB

  2. Byte-by-byte match {0x32, 0x54, 0xCD, 0xAB}

  3. Magic number offset +0x10 → Read 32-byte version

  4. Verify first character is '0'~'9'

6.5 OTA Core APIs

OTA operations follow six-step process: "Get partition → Begin write → Write in chunks → End verification → Set boot partition → Reboot switch", each step corresponds to one core API.

xxxxxxxxxx
// Get "next" writable OTA partition (the one outside current 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 per chunk)
esp_ota_write(handle, data, size);

// End write (verify + close)
esp_ota_end(handle);

// Set 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 .bin files. For testing, you can start a simple server on PC:

PC side executes one command to start HTTP server, ESP32 accesses this address via WiFi to download firmware.

xxxxxxxxxx
# Python 3 one-command HTTP server (port 8080, root = current directory)
python -m http.server 8080

# On Windows, ensure firewall allows port 8080

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

6.7 OTA Precautions

Key PointDescription
Partition table must include OTA partitionsmenuconfig → Partition Table → "Factory app, two OTA definitions"
Firmware size limitota_0/ota_1 each occupy half of Flash minus factory, exceeds causes esp_ota_write failure
Network stabilityWiFi disconnects mid-download → esp_ota_abort() rollback, device still runs old version
Version number formatPure number + dots (1.0.0), don't include v prefix
SecurityProduction should use HTTPS + certificate verification + firmware signature to prevent man-in-the-middle attacks
RollbackESP-IDF supports automatic rollback - if new firmware reboots continuously N times, automatically switches back to old version

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


7. WiFi Common Troubleshooting

SymptomCauseSolution
Continuously prints "Disconnected, reconnecting..."SSID or password incorrectCheck WIFI_SSID and WIFI_PASS macros
Connecting to 5G WiFi failsESP32-S3 only supports 2.4GEnsure router 2.4G band is enabled
Got IP but can't ping external networkRouter not connected to internet / DNS issuePing router IP first to confirm LAN connectivity
esp_wifi_connect() returns errorWiFi initialization not completeEnsure vTaskDelay(500ms) after esp_wifi_start()
WIFI_EVENT_STA_DISCONNECTED triggers frequentlyWeak signal or crowded router channelMove closer to router / Change WiFi channel
Compilation error nvs_flash.h not foundNVS not initializedAdd nvs_flash_init() at the beginning of app_main()
AP mode phone can't find hotspotChannel occupied / Not started normallyCheck logs confirm WiFi AP started; Try changing AP_CHANNEL
AP mode connection shows "password incorrect"Password less than 8 charactersWPA2 requires password ≥ 8 characters

Common Network Communication Protocols


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


1. TCP/IP Protocol Stack

1.1 Layered Model

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

xxxxxxxxxx
┌─────────────────────────────────────────────┐
│              Application Layer              │  HTTP / MQTT / DNS / OTA
│  http://example.com/api  →  "Hello ESP32"   │
├─────────────────────────────────────────────┤
│              Transport Layer                │  TCP / UDP
│  Port (80/8080/1883) + reliable/unreliable transmission        │
├─────────────────────────────────────────────┤
│              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
Network Layer:  [ IP header | src=192.168.1.100 dst=93.184.216.34 | TCP header | HTTP GET ... ]
                    ↓ Add WiFi frame header
Link Layer:  [ WiFi header | src=AA:BB:CC dst=DD:EE:FF | IP header | TCP header | HTTP GET ... | FCS checksum ]

Receiving end unpacks layer by layer until application layer gets raw data.

1.3 Key Protocol Comparison

ProtocolLayerReliabilityConnectionHeader OverheadTypical Use
IPNetwork LayerUnreliableConnectionless20BAddressing, routing
ICMPNetwork LayerUnreliableConnectionless8BPing, error reporting
TCPTransport LayerReliableConnection-oriented20BWeb, files, MQTT
UDPTransport LayerUnreliableConnectionless8BDNS, video streaming, sensors
ARPLink Layer——28BIP→MAC address resolution
DHCPApplication Layer———Auto IP assignment

2. IP Address

IP address is the "house number" for network communication - after ESP32 gets IP, it can be accessed by other devices on LAN, which is prerequisite for all subsequent Socket communication, HTTP requests, and MQTT connections.

2.1 IPv4 Basics

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

xxxxxxxxxx
192     .   168     .   1       .   100
11000000  10101000  00000001  01100100     ← 32-bit binary
└──────────────┬──────────────┘└───┬───┘
            Network part           Host part
       (subnet mask determines boundary)

2.2 Subnet Mask

Subnet mask determines which part of IP address is "network number" and which part is "host number":

Subnet MaskCIDRAvailable 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 (0~255, where 0=network, 255=broadcast)

All devices on the same network have the same "network part", different "host part".

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 router
OthersPublic IPUnique on internet, requires purchase

Private IP cannot be accessed directly from internet - router maps private IP to public IP through NAT (Network Address Translation).

2.4 Special IP Addresses

IPMeaningUsage
127.0.0.1LocalhostAccess yourself
0.0.0.0Any addressBind to all network interfaces
255.255.255.255Broadcast addressSend to all devices on LAN
192.168.1.1Usually router gatewayManagement page entry

3. Port

Port is the key to achieving "one device, multiple services" - ESP32 can simultaneously run HTTP server (80), MQTT client (1883), and TCP data channel (8080), each service binding different ports without interference. Firewall and NAT configurations also depend on port numbers.

3.1 Concept of Port

IP address locates a device, port locates a program on that 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 │ 
                 └────────────────────────────┘

Port is a 16-bit number (0~65535):

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

3.2 Client Port vs Server Port

xxxxxxxxxx
Client (Browser/ESP32)                    Server
─────────────────────────        ─────────────────
socket()                            socket()
(System auto-assigns temp port,           bind(80)           ← Must fix port,
 like 52341)                                              client knows which port to connect
connect(93.184.216.34:80) ──────→  listen(80) + accept()
                                    Connection received: client IP:52341 ↔ server IP:80
send() ──────────────────────────→  recv() → process → send()
recv() ←──────────────────────────  (reply)

Server must bind() fixed port, otherwise client doesn't know where to connect; client port is auto-assigned by OS (discarded after use).


4. Socket Programming Basics

Socket is the core API layer for network programming in ESP-IDF - whether custom TCP/UDP communication, HTTP client or MQTT client, all underlying data is sent/received via Socket. Mastering Socket data structures, byte order conversion, and creation methods is the foundation for reading and writing all network code.

4.1 What is Socket

Socket is a network programming interface provided by the operating system - developers send/receive data through Socket without caring about underlying WiFi frames, IP fragmentation, TCP retransmission and other details.

xxxxxxxxxx
Application code                    OS kernel
──────────                          ─────────────
send(sock, "Hello", 5)
    │                          ┌─────────────┐
    └──────────────────────────→   TCP stack │ → Fragment → Add TCP header
                               ├─────────────┤
                               │   IP stack  │ → Fragment → Add IP header → Route
                               ├─────────────┤
                               │  WiFi driver│ → Add WiFi frame → DMA → Antenna transmit
                               └─────────────┘

4.2 Key Data Structures

Two most important address structures in Socket programming - sockaddr is generic type, sockaddr_in is IPv4-specific type, all Socket APIs use latter via casting.

xxxxxxxxxx
// Generic Socket address (supports 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 - high-order byte stored at low address. ESP32 CPU is little-endian, opposite of network order, must convert:

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
FunctionMeaningUsage
htons(n)Host TO Network Short (16-bit)Port conversion
htonl(n)Host TO Network Long (32-bit)IP address conversion (less used)
ntohs(n)Network TO Host ShortRestore after receiving
ntohl(n)Network TO Host LongRestore after receiving
inet_pton()String → Binary IP (auto network order)"192.168.1.1" → 0x0101A8C0

Ports and IP addresses need conversion to network byte order - htons() for ports, inet_pton() converts IP string to network-order binary.

xxxxxxxxxx
// Correct approach: 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 approach: direct assignment
// ❌ CPU little-endian, network sees 0x901F
addr.sin_port = 8080;

4.4 Socket Creation Types

socket() distinguishes TCP (stream) from UDP (datagram) via type parameter - this determines communication mode for all subsequent Socket operations.

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 transmission protocol for IoT devices - firmware OTA upgrades cannot lose a single byte, MQTT messages must be reliably delivered, HTTP pages must load completely, all these scenarios rely on TCP's acknowledgment and timeout retransmission mechanism. Understanding three-way handshake, four-way wave (connection termination), and recv() return values is the foundation for stable TCP server operation.

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 connection

  • SYN+ACK: Agree + Request (server also confirms its direction)

  • ACK: Acknowledge (formally established)

The essence of three-way handshake is each party confirms the other's send/receive capability is normal.

5.2 Four-Way Wavehand

xxxxxxxxxx
    Client                                 Server
    ────────                              ────────
    close() or shutdown()
    │──── FIN (seq=u) ──────────────────→│  Client: "I'm done sending data"
    │←─── ACK (ack=u+1)  ────────────────│  Server: "Got it"
    │                                    │  (Server may still have data to send)
    │←─── FIN (seq=v)  ──────────────────│  Server: "I'm done too"
    │──── ACK (ack=v+1) ────────────────→│  Client: "Got it"
    │                                    │
    ═══════ Connection Closed ═════════════════

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

5.3 How Reliable Transmission is Achieved

TCP's reliability comes from three mechanisms:

MechanismPrinciple
Acknowledgment (ACK)Reply ACK after receiving data, sender retransmits if no ACK received
Sequence Number (SEQ)Each byte has a number, receiver reassembles in order
Timeout Retransmission (RTO)Timer starts after sending, retransmit if ACK not received within timeout

5.4 Three Cases of recv() Return Value

Return ValueMeaningHandling
> 0Received n bytes of dataNormal processing
= 0Peer closed connection normally (sent FIN)close() and break
< 0No data yet (MSG_DONTWAIT mode) or errorCheck errno

recv() three return values 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 + close() */ }
else             { /* No data (non-blocking), or real error */ }

5.5 TCP Server Standard Flow

xxxxxxxxxx
socket() → bind() → listen() → while(1) {
    client_fd = accept() → while(1) {
        recv() / send()    ← Communicate with single client
    } → close(client_fd)   ← Client disconnected, return to accept
}

6. UDP In-Depth

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

6.1 What "Connectionless" Means

UDP doesn't handshake, doesn't establish connection, doesn't guarantee delivery - datagrams are like throwing a message in a bottle (drift bottle):

xxxxxxxxxx
     Client (ESP32)                              Server (PC)
     ──────────────                            ─────────────
     socket(SOCK_DGRAM)                        socket(SOCK_DGRAM) + bind(8080)
     │                                          │
     │── sendto("Hello", 192.168.1.183:8080) ──→│  Send directly
     │                                          │  (Received if received, missed if missed)
     │←─ sendto("Reply", 192.168.1.100:52341) ──│  Reply

6.2 UDP Applicable Scenarios

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

6.3 UDP vs TCP API Comparison

TCP vs UDP API call flow comparison - TCP requires listen() + accept() to establish connection then communicates via file descriptor, UDP directly uses sendto()/recvfrom() with 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, use recvfrom directly
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)

MSG_DONTWAIT flag makes recvfrom()/recv() non-blocking - returns -1 immediately (errno=EAGAIN) when no data, without blocking task, suitable for high-frequency polling scenarios (e.g., 10ms interval low-latency receive loop).

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 configurations, POST to report sensor data, Range requests to implement OTA firmware chunked download. Understanding request/response format and status codes is 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                                  ← Empty line = end of headers
                                       ← Request body (empty for GET, has 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                                   ← Empty line = end of headers
<html>...response body...</html>       ← Response body

7.3 Common Status Codes

Status CodeMeaningDescription
200OKRequest successful
206Partial ContentRange request returns partial content (OTA firmware header download)
301Moved PermanentlyPermanent redirect
302FoundTemporary redirect
400Bad RequestRequest format error
404Not FoundResource does not exist
500Internal Server ErrorServer internal error

7.4 Common HTTP Methods

MethodSemanticsRequest BodyTypical Use
GETGet resourceNoneQuery data, fetch webpage
POSTSubmit dataHasSubmit forms, upload sensor data
PUTReplace resourceHasUpdate configuration
DELETEDelete resourceNoneDelete record

8. MQTT Protocol Basics

8.1 Why IoT Uses MQTT Instead of HTTP

ComparisonMQTTHTTP
Communication ModelPublish/Subscribe (Broker relay)Request/Response (direct)
Message PushNative support, subscribe = pushRequires client polling (or WebSocket)
Min Protocol Header2 bytesHundreds of bytes
Connection Keep-aliveKeep Alive heartbeatStateless (each request independent connection)
One-to-ManyNaturally supported (multiple people subscribe same Topic)Requires server polling + push logic

8.2 Publish/Subscribe Model

xxxxxxxxxx
                  ┌─────────────┐
                  │ MQTT Broker │      ← Core: all messages routed by Broker
                  │ (Message Broker) │
                  └──┬───────┬──┘
    Subscribe              │       │          Subscribe
 sensor/temp     ┌────┘       └────┐ sensor/alert
                   │                 │
             ┌─────┴─────┐     ┌─────┴─────┐
             │Temp Sensor│     │ Monitor   │
             │ publish() │     │ automatically receives │
             │sensor/temp│     │ temp data │
             └───────────┘     └───────────┘

Three Roles:

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

8.3 Topic Wildcards

WildcardSemanticsExample
+Match single levelhome/+/light → home/bedroom/light
#Match multiple levelshome/# → home/bedroom/light/status

8.4 QoS Three Levels

QoSSemanticsMechanism
0At most once (fire and forget)No retry, no acknowledgment
1At least once (may duplicate)Send → Wait for PUBACK → Timeout retransmit
2Exactly once (no duplicates)PUBREC→PUBREL→PUBCOMP four-way handshake

9. ESP-IDF Network API Selection Guide

When developing network applications, ESP-IDF provides from low-level to high-level APIs, select based on requirements:

xxxxxxxxxx
High-level (simple, well-encapsulated)
  │  esp_http_client / esp_http_server    ← HTTP request/server
  │  mqtt_client                          ← MQTT client
  │  esp_ota                              ← OTA upgrade
  │
  │  lwip/sockets (BSD Socket API)        ← TCP/UDP raw communication
  │    socket / bind / listen / accept / connect
  │    send / recv / sendto / recvfrom
  │
Low-level (flexible, need manual handling)
  │  esp_wifi                             ← WiFi connect/scan/config
  │  esp_netif                            ← Network interface management
  │  esp_event                            ← Event-driven framework
If you want to do...Use this API
Connect to WiFiesp_wifi + esp_netif
Custom TCP/UDP communicationlwip/sockets (BSD Socket)
Access webpage / REST APIesp_http_client
Build Web serveresp_http_server
IoT sensor reporting / remote controlmqtt_client
WiFi remote firmware upgradeesp_ota + esp_http_client
Ping remote hostlwip/ping.h or esp_ping

10. Common Debug Methods

Network problem troubleshooting uses layer-by-layer localization strategy - confirm from bottom to top: WiFi connection → IP obtained → LAN connectivity → Port listening → Application layer protocol. Skipping levels easily leads to confusion.

10.1 Troubleshooting Steps

xxxxxxxxxx
Problem: ESP32 cannot communicate

1. First check if serial logs show "Got IP: xxx.xxx.xxx.xxx"
   ├─ No → WiFi not connected → Check SSID/password/frequency band
   └─ Yes → WiFi normal, continue troubleshooting

2. Ping test
   ├─ Ping ESP32 IP     → Verify IP layer connectivity
   ├─ Ping router IP    → Verify LAN connectivity
   └─ Ping 8.8.8.8      → Verify internet connectivity (DNS unrelated, pure IP)

3. Port test
   ├─ On PC use netstat -an | findstr 8080 to check if port is listening
   └─ Use network debug tool to send data to ESP32 IP:PORT

4. Firewall check
   └─ Windows firewall may block non-standard ports like 8080

10.2 Common Debug Commands

PC side and ESP32 side commonly used network debug commands - first confirm network connectivity from PC side, then confirm running status from 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 IP incorrectConfirm PC side Server is listening, IP and port correct
bind() failsPort already in useChange port number / Wait 2 minutes (TIME_WAIT timeout)
recv() returns 0Peer actively closed connectionNormal disconnect, break then close()
recv() data "sticks together"TCP is byte stream, no message boundariesApplication layer defines frame header+length or delimiter protocol
send() continuous failuresPeer closed / network interruptedTCP connection disconnected, need to connect() again
Chinese text garbledTerminal encoding mismatchCheck serial assistant and network debug tool encoding settings (UTF-8)
PC cannot receive ESP32 dataESP32 IP changed / firewall blockedCheck ESP32 actual IP via serial, PC firewall allows corresponding port
HTTP client HTTP request errorURL unreachable or DNS resolution failedEnsure ESP32 can access internet; or use IP instead of domain name
MQTT MQTT_EVENT_CONNECTED doesn't triggerBroker address incorrect or WiFi no internetping broker.emqx.io to test internet connectivity
Priority Inversion
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
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文