Note: This tutorial uses the ESP32 development board to connect to a WiFi router, which is the first step in learning ESP32 wireless communication. Please make sure your ESP32 has the correct drivers and board core support installed.
WiFi is a wireless local area network technology that allows electronic devices to connect to a network via radio waves. It is everywhere in daily life—phones, computers, and smart home devices all rely on WiFi to access the internet. This project simply makes the ESP32 board "connect to your home WiFi" just like a smartphone does.
Simple analogy: WiFi is like an "invisible web," the router is the "center of the spider web," and the ESP32 is a "little insect"—once it gets on the web, it can communicate with other insects (computers, phones).
ESP32's WiFi has two working modes. Beginners need to understand the difference:
| Mode | Full Name | Analogy | Description |
|---|---|---|---|
| STA | Station | Phone connecting to router | ESP32 acts as a "client" connecting to an existing WiFi hotspot |
| AP | Access Point | The router itself | ESP32 creates its own WiFi hotspot for other devices to connect to |
| AP+STA | Both modes simultaneously | Both a router and a client | Can connect to others and be connected to by others |
This tutorial uses STA mode, where the ESP32 connects to your home or office WiFi router.
ESP32 is an IoT development board developed by Espressif:
The process of connecting an ESP32 to a WiFi router consists of four steps:
│ 1. Set Mode│ → │ 2. Begin │ → │ 3. Wait for │ → │ 4. Get Info │
│ WIFI_STA │ │ WiFi.begin │ │ WiFi.status │ │ IP / MAC │
24:6F:28:A4:B2:C1), determined by hardware192.168.1.105), automatically assigned by the router-50 is better than -80)When the WiFi signal is unstable, the device may disconnect. The auto-reconnect mechanism allows the device to automatically attempt to reconnect after a disconnection:
millis() for timing, checking the connection status at fixed intervalsWiFi.reconnect() when a disconnection is detectedSimple analogy: Just like a phone automatically reconnects to WiFi after a disconnection, without requiring manual operation.
This project uses the WiFi library built into the ESP32 board. It is automatically available after installing the ESP32 core.
https://dl.espressif.com/dl/esp32/esp32-arduino-index.json
esp32 and install esp32 by Espressif Systems| Function | Description | Role in This Project |
|---|---|---|
WiFi.mode(mode) |
Set WiFi working mode | Set to WIFI_STA station mode |
WiFi.begin(ssid, password) |
Initiate WiFi connection | Connect to the router using the specified SSID and password |
WiFi.status() |
Get current WiFi status | Determine whether the connection succeeded (returns WL_CONNECTED, etc.) |
WiFi.localIP() |
Get local IP address | Print the IP obtained by the ESP32 |
WiFi.macAddress() |
Get MAC address | Print the ESP32's physical address |
WiFi.RSSI() |
Get signal strength | Print the current WiFi signal strength (dBm) |
WiFi.reconnect() |
Attempt to reconnect | Automatically reconnect when disconnected |
| Constant | Value | Description |
|---|---|---|
WL_IDLE_STATUS |
0 | Idle status, not connected |
WL_NO_SSID_AVAIL |
1 | Specified SSID not found |
WL_SCAN_COMPLETED |
2 | Scan completed |
WL_CONNECTED |
3 | Successfully connected |
WL_CONNECT_FAILED |
4 | Connection failed |
WL_CONNECTION_LOST |
5 | Connection lost |
WL_DISCONNECTED |
6 | Disconnected |
This project mainly checks
WiFi.status() == WL_CONNECTEDto confirm the connection status.
| Function | Description | Role in This Project |
|---|---|---|
millis() |
Milliseconds since boot | Calculate reconnect interval, implement non-blocking timing |
delay(ms) |
Blocking delay | Pause for 500ms during connection wait, giving the router time to respond |
#include <WiFi.h>
// ==================== WiFi Credentials ====================
const char* ssid = "ZNP"; // Replace with your WiFi name
const char* password = "16881688"; // Replace with your WiFi password
// ==================== Variables ====================
unsigned long previousMillis = 0;
const long interval = 5000; // Reconnect check interval (ms)
Code Explanation:
#include <WiFi.h>: Includes the ESP32 WiFi library, providing all WiFi-related functionsssid: WiFi name (Service Set Identifier), the "name" of the router—this is what you see when connecting your phone to WiFipassword: WiFi password, the router's encryption passphrasepreviousMillis: Records the timestamp of the last reconnect checkinterval: Reconnect check interval (5000ms = 5 seconds); the connection status is checked every this oftenYou need to change
ssidandpasswordto your own WiFi name and password.
setup() Initialization Functionsetup() runs only once after the ESP32 powers on, and is responsible for completing all WiFi connection initialization.
Serial.begin(115200);
delay(1000);
Serial.println("\n====================");
Serial.println("ESP32 WiFi Tutorial");
Serial.println("====================");
Step Analysis:
Serial.begin(115200): Initializes the serial port with a baud rate of 115200, used to send debug information to the computerdelay(1000): Waits 1 second for the serial port to stabilize, avoiding missing early outputSerial.println(): Prints a welcome banner to confirm the program is running normallyWiFi.mode(WIFI_STA);
Serial.println("WiFi mode set to STA (Station)");
Code Analysis:
WiFi.mode(WIFI_STA): Sets the ESP32 to STA (Station) modeWiFi.begin()Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
Code Analysis:
WiFi.begin(ssid, password): Sends a connection request to the specified WiFi routerint attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
Code Analysis:
This is a blocking wait loop with the following logic:
WiFi.status(): Queries the current connection status in real time!= WL_CONNECTED: As long as it's not connected, keep waitingattempts < 20: Wait at most 20 times, 500ms each time, totaling about 10 secondsdelay(500): Pause for 500ms before checking again, giving the router time to processSerial.print("."): Prints a dot in the serial monitor so you can see the waiting progressConnecting a phone to WiFi also takes a few seconds, and the same is true for the ESP32. If the password is wrong or the signal is too weak, it will give up after 20 attempts.
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\n✅ WiFi Connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP()); // e.g. 192.168.1.105
Serial.print("MAC Address: ");
Serial.println(WiFi.macAddress()); // e.g. 24:6F:28:A4:B2:C1
Serial.print("RSSI (signal strength): ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
} else {
Serial.println("\n❌ WiFi Connection Failed!");
Serial.println("Please check your SSID and password.");
}
Code Analysis:
When connection succeeds, it prints three key pieces of information:
WiFi.localIP(): The IP address assigned to the ESP32 by the router (e.g., 192.168.1.105), which is needed for subsequent HTTP/WebSocket communicationWiFi.macAddress(): The hardware address of the ESP32, used for network device identificationWiFi.RSSI(): Signal strength (in dBm); values closer to 0 are better (-50 is strong, -80 is weak)When connection fails, it prints an error message reminding you to check the SSID and password
loop() Main Loop Functionloop() is called repeatedly after setup() finishes. It is the "heartbeat" of the program.
void loop() {
// ---------- Auto-reconnect logic ----------
if (WiFi.status() != WL_CONNECTED) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
Serial.println("WiFi lost. Attempting to reconnect...");
WiFi.reconnect();
}
}
// Your main application code goes here
// e.g. HTTP client, WebSocket, MQTT, etc.
delay(100);
}
Step-by-Step Analysis of Core Logic:
Step 1: Detect Disconnection
if (WiFi.status() != WL_CONNECTED) {
Each loop checks the WiFi status. If it's not equal to WL_CONNECTED, it means the connection has been lost or was never established.
Step 2: Non-Blocking Timing
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
Uses millis() to implement non-blocking timing:
millis() returns the number of milliseconds since the ESP32 booted (overflows after about 50 days)currentMillis - previousMillis calculates how long it has been since the last checkinterval (5 seconds) has passed, avoiding excessive frequencyWhy use
millis()instead ofdelay()? Becausedelay()blocks the entire program, while withmillis()the main loop can continue executing other tasks during the timing period.
Step 3: Perform Reconnection
Serial.println("WiFi lost. Attempting to reconnect...");
WiFi.reconnect();
WiFi.reconnect(): Tells the ESP32 to send a new connection request to the routerpreviousMillis = currentMillis: Resets the timer to start timing for the next reconnect attemptStep 4: Short Delay
delay(100);
Pauses for 100ms each loop, giving the hardware and network time to process and avoiding CPU overload.
Open wifi_connect.ino and modify these two lines:
const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";
Note: ESP32 only supports 2.4GHz WiFi, not 5GHz. Please make sure your router has the 2.4G band enabled.
====================
ESP32 WiFi Tutorial
====================
WiFi mode set to STA (Station)
Connecting to ZNP_2.4G
.....
✅ WiFi Connected!
IP Address: 192.168.1.105
MAC Address: 24:6F:28:A4:B2:C1
RSSI (signal strength): -45 dBm
====================
ESP32 WiFi Tutorial
====================
WiFi mode set to STA (Station)
Connecting to MyWiFi
....................
❌ WiFi Connection Failed!
Please check your SSID and password.
WiFi lost. Attempting to reconnect...
WiFi lost. Attempting to reconnect...
.....
✅ WiFi Connected!
IP Address: 192.168.1.105
...
Q1: The Serial Monitor shows garbled characters?
A: Please make sure the baud rate of the Serial Monitor is set to 115200 (bottom right dropdown).
Q2: The serial shows "WiFi Connection Failed"?
A: Please check the following in order:
Q3: The serial only prints a few dots and then stops?
A: The board model may be selected incorrectly. Please confirm you have selected the correct ESP32 model (e.g., ESP32 Dev Module, ESP32S3 Dev Module, etc.).
Q4: The RSSI value is -80 or lower?
A: The signal is weak. It is recommended to shorten the distance between the ESP32 and the router, or use an ESP32 module with an external antenna.
Q5: No output at all after uploading the program?
A: Please check:
Q6: WiFi disconnects shortly after connecting?
A: Possible causes:
| Problem | Possible Cause | Solution |
|---|---|---|
| Garbled serial output | Wrong baud rate | Change to 115200 |
| Cannot upload | Wrong port / missing driver | Check port and CH340/CP2102 driver |
| WiFi won't connect | Wrong SSID/password | Double-check case and spaces |
| WiFi won't connect | 5GHz band | Use 2.4GHz |
| Weak signal | Too far / obstruction | Move closer to router or use an antenna |
| Frequent disconnections | Insufficient power | Use an independent 5V power supply |
| Reconnect too slow | Interval too long | Modify the interval variable |
Modify the interval variable in the code:
const long interval = 3000; // Change to 3 seconds, more frequent reconnection
const long interval = 10000; // Change to 10 seconds, fewer checks
If you need a fixed IP instead of dynamic allocation, add the following before WiFi.begin():
IPAddress ip(192, 168, 1, 150); // Target static IP
IPAddress gateway(192, 168, 1, 1); // Router gateway
IPAddress subnet(255, 255, 255, 0); // Subnet mask
WiFi.config(ip, gateway, subnet);
Scan nearby WiFi networks before connecting:
WiFi.mode(WIFI_STA);
int n = WiFi.scanNetworks();
Serial.print("Found ");
Serial.print(n);
Serial.println(" networks:");
for (int i = 0; i < n; i++) {
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.println(" dBm)");
}
Add actual functionality at the commented location in loop():
void loop() {
if (WiFi.status() != WL_CONNECTED) {
// ... reconnect logic ...
}
// Add your application code here
// e.g., send a heartbeat to the server every 30 seconds
static unsigned long lastSend = 0;
if (millis() - lastSend > 30000) {
lastSend = millis();
Serial.println("Sending heartbeat...");
// HTTP client, MQTT publish, etc.
}
delay(100);
}
If you want the ESP32 to create its own hotspot for other devices to connect to (instead of connecting to a router):
// AP mode example
const char* apSSID = "ESP32_AP";
const char* apPassword = "12345678";
void setup() {
WiFi.mode(WIFI_AP);
WiFi.softAP(apSSID, apPassword);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
}
ESP32 only supports 2.4GHz WiFi, not 5GHz. If your router only has the 5GHz band enabled, the ESP32 will not be able to connect. Please enable 2.4GHz in your router settings.
The WiFi password must be at least 8 characters long. If your router's password is too short, please change the router password or use a different network.
The ESP32's WiFi function consumes a lot of power (peak can reach 300mA). It is recommended to use an independent 5V power supply through the VIN pin, rather than relying solely on USB.
The auto-reconnect logic uses millis() for a non-blocking design, but WiFi.reconnect() itself is blocking (about 1 second). In practical applications, if high real-time performance is required, you can use WiFi.begin() to re-initiate the connection instead.
Connecting to public WiFi (such as cafes, campus networks) may require web authentication (Portal), which the ESP32 cannot complete. Please use an open or WPA2-encrypted network.
When the SSID contains Chinese or special characters, encoding issues may occur. It is recommended to use an SSID with only English letters and numbers.