WiFi & Networking on ESP32
WiFi & Networking on ESP32
Connect to a network, make HTTP requests, and host a simple web server.
WiFi on the ESP32
The ESP32 has a fully integrated WiFi stack. The WiFi.h library (included with the ESP32 Arduino core) exposes everything you need to connect, scan, and serve data.
Connecting to a WiFi Network (Station Mode)
Station mode means the ESP32 connects to an existing WiFi router ߀” just like a phone or laptop.
#include <WiFi.h>
const char* ssid = "YourNetworkName";
const char* password = "YourPassword";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
}
void loop() { }
WiFi Status Codes
| Constant | Value | Meaning |
|---|---|---|
WL_CONNECTED |
3 | Connected to an AP |
WL_DISCONNECTED |
6 | Not connected |
WL_CONNECT_FAILED |
4 | Wrong password |
WL_NO_SSID_AVAIL |
1 | SSID not found |
Making an HTTP GET Request
Use the HTTPClient library to call REST APIs or fetch web pages:
#include <WiFi.h>
#include <HTTPClient.h>
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("http://worldtimeapi.org/api/ip");
int httpCode = http.GET();
if (httpCode == 200) {
String payload = http.getString();
Serial.println(payload);
}
http.end();
}
delay(10000);
}
Hosting a Simple Web Server
Access Point + Web Server mode lets the ESP32 create its own WiFi network and serve pages:
#include <WiFi.h>
#include <WebServer.h>
WebServer server(80);
void handleRoot() {
server.send(200, "text/html",
"<h1>ESP32 Web Server</h1><p>GPIO 2: ON</p>");
}
void setup() {
WiFi.begin("YourSSID", "YourPassword");
while (WiFi.status() != WL_CONNECTED) delay(500);
server.on("/", handleRoot);
server.begin();
Serial.println("Server started at: " + WiFi.localIP().toString());
}
void loop() {
server.handleClient();
}
Scanning for Networks
int n = WiFi.scanNetworks();
for (int i = 0; i < n; i++) {
Serial.print(WiFi.SSID(i));
Serial.print(" RSSI: ");
Serial.println(WiFi.RSSI(i));
}
Access Point (AP) Mode
The ESP32 can create its own WiFi hotspot:
WiFi.softAP("ESP32-Hotspot", "password123");
Serial.println(WiFi.softAPIP()); // Usually 192.168.4.1
Using HTTPS
For HTTPS you need the WiFiClientSecure library:
#include <WiFiClientSecure.h>
WiFiClientSecure client;
client.setInsecure(); // Skip certificate validation (not for production)
Tips for Reliable WiFi
- Always check
WiFi.status() == WL_CONNECTEDbefore making requests - Use
WiFi.setAutoReconnect(true)to reconnect automatically after drops - Avoid
delay()insideloop()when running a web server ߀” usemillis()for timing - Use
WiFi.disconnect(true)andWiFi.begin()again to force a reconnect