Wi-Fi: connect your ESP32 to a network
The ESP32 has a complete built-in 2.4 GHz Wi-Fi radio. It can join an existing network as a laptop does (station mode). It can also make its own hotspot (access-point mode), or do the two at the same time. When it is connected, it can serve a web page that you open on your phone. It can also get data from the internet and set its clock with NTP.

Photo: Brian Krent, CC BY-SA 4.0
Serial Monitor (115200 baud)
Station, access point, or the two together
WiFi.softAP("ESP32-Lab", "password123"). The password must have a minimum of 8 characters. WIFI_AP_STA operates the two modes at the same time.Signal strength (RSSI)
How to read dBm
- dBm is a logarithmic power scale. The values are negative. A value nearer to 0 is stronger.
- −3 dB ≈ half the power. −10 dB = one tenth, so −70 dBm is 1000× weaker than −40 dBm.
- Walls, metal, water (also people) and distance decrease the signal. The PCB antenna of the DevKit is small. Keep the antenna away from metal and from the power rails of the breadboard.
- Boards with a u.FL connector (WROOM-32U) can use an external antenna for a longer range.
Control an LED from your phone
A web server is a program that waits for HTTP requests and sends back responses. When you push a
button on the page, the page asks the ESP32 for a URL such as /led/on. The ESP32 runs the related handler and switches the
GPIO pin. Then it sends back a new page.
ESP32 LED
The data that Wi-Fi sends
Push a button on the phone…
ESP32 (GPIO 2)
The ESP32 waits for a request.
Usual problems
2.4 GHz only
The original ESP32 supports only 2.4 GHz networks. Home routers often put 2.4 and 5 GHz under one name. This usually operates correctly. A 5 GHz-only network or phone hotspot shows as “network not found”. On iPhones, enable Maximize Compatibility.
Campus / enterprise Wi-Fi
Networks such as eduroam use WPA2-Enterprise (username + password + certificates). The ESP32 can do this through
an added WiFi.begin() overload. But this is difficult, and the campus policy possibly does not permit it. Many campuses have a separate
IoT / device network. On this network, you register the MAC address of your board. Speak to your IT department or makerspace.
Print your MAC address with WiFi.macAddress().
Do not put passwords in Git
Put your SSID and password in a secrets.h file. Use #include to include the file. Add the file to .gitignore.
Thousands of Wi-Fi passwords are on GitHub because persons did not do this.
Do not use ADC2 with Wi-Fi
The Wi-Fi driver uses ADC2, so analogRead() on ADC2 pins (GPIO 0, 2, 4, 12–15, 25–27) fails when Wi-Fi is on.
For analog sensors, use ADC1 pins (32–39). Refer to GPIO.
Brownouts
When the radio transmits, it uses short current spikes of a few hundred mA. A weak USB port, a long thin cable or a shared motor supply can decrease the voltage. Then the board resets with a “Brownout detector was triggered” message. Refer to Power supplies.
Do not block the loop
server.handleClient() must run frequently. Long delay() calls make the web page stop responding.
For all other timing in loop(), use millis().
Step-by-step
- Make secrets.h. Put it in the same folder as your sketch. Write
#define WIFI_SSID "..."and#define WIFI_PASS "..."in it. - Connect. Upload the connect sketch. Open the Serial Monitor at 115200 baud. Write down the IP address.
- Run the LED web server. Upload the sketch. Connect a phone to the same network. On the phone, open
http://<that IP>/orhttp://esp32.local/. - Get data. Try the HTTP + JSON example (it needs the ArduinoJson library).
- Set the clock. Use NTP. Then your logs and displays show the real time.
Troubleshooting
- Only dots “……” show: Examine the SSID spelling (upper and lower case are different), the password, the 2.4 GHz band and the distance.
- Connected, but the page does not open: The phone is on a different network (guest Wi-Fi isolates devices), or the IP address changed.
esp32.localdoes not resolve: Some Android versions and Windows installations do not have mDNS. Use the IP address.- HTTPS requests fail: Use
WiFiClientSecure. For quick tests,setInsecure()does not do certificate checks. For finished projects, verify the server withsetCACert().
Code
0 · secrets.h (your Wi-Fi password)
In the Arduino IDE, click the ⋯ menu at the right of the file tabs → New Tab, and name it
secrets.h. The file goes into the sketch folder. Each sketch below uses #include "secrets.h".
secrets.h
// secrets.h — private settings for this sketch.
// Do not commit this file. Add it to .gitignore.
#pragma once
#define WIFI_SSID "MyNetwork" // 2.4 GHz network name (case-sensitive)
#define WIFI_PASS "MyPassword123" // Wi-Fi password
// Optional: other private values for the same project
// #define API_KEY "abc123..."
// #define OTA_PASS "change-me"
.gitignore
# Do not upload passwords to GitHub
secrets.h
To share a project, commit a copy named secrets.example.h with placeholder values. Each user copies it to
secrets.h and types in their own values.
1 · Connect (with timeout)
wifi_connect.ino
#include <WiFi.h>
#include "secrets.h" // #define WIFI_SSID "..." / #define WIFI_PASS "..."
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
Serial.print("MAC address: ");
Serial.println(WiFi.macAddress()); // register this address on campus device networks
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < 15000) {
delay(500);
Serial.print(".");
}
if (WiFi.status() == WL_CONNECTED) {
Serial.print("\nConnected! IP: ");
Serial.println(WiFi.localIP());
Serial.printf("Signal: %d dBm\n", WiFi.RSSI());
} else {
Serial.printf("\nFailed, status = %d\n", WiFi.status());
}
WiFi.setAutoReconnect(true); // connect again if the router disconnects (on by default)
}
void loop() {}
3 · Fetch JSON from the internet
This example needs the ArduinoJson library (v7). It asks Open-Meteo for the current temperature in Amherst, MA.
http_json.ino (after connecting)
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
void printTemperature() {
WiFiClientSecure client;
client.setInsecure(); // for tests only: no certificate check
HTTPClient http;
http.begin(client, "https://api.open-meteo.com/v1/forecast"
"?latitude=42.39&longitude=-72.53¤t=temperature_2m");
int code = http.GET();
if (code == 200) {
JsonDocument doc;
deserializeJson(doc, http.getString());
float t = doc["current"]["temperature_2m"];
Serial.printf("Temperature: %.1f C\n", t);
} else {
Serial.printf("HTTP error %d\n", code);
}
http.end();
}
2 · Web server: LED on/off from a phone
wifi_led_server.ino
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include "secrets.h"
const int LED_PIN = 2;
WebServer server(80);
bool ledOn = false;
void sendPage() {
String html = "<!doctype html><meta name='viewport' content='width=device-width'>"
"<h1>ESP32 LED</h1><p>LED is " + String(ledOn ? "ON" : "OFF") + "</p>"
"<p><a href='/led/on'>Turn ON</a> | <a href='/led/off'>Turn OFF</a></p>";
server.send(200, "text/html", html);
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(250);
Serial.println(WiFi.localIP());
MDNS.begin("esp32"); // http://esp32.local/
server.on("/", sendPage);
server.on("/led/on", []() { ledOn = true; digitalWrite(LED_PIN, HIGH); sendPage(); });
server.on("/led/off", []() { ledOn = false; digitalWrite(LED_PIN, LOW); sendPage(); });
server.begin();
}
void loop() {
server.handleClient(); // call frequently; do not use long delay()s
}
4 · Real time with NTP
ntp_clock.ino (after connecting)
#include <time.h>
void setupClock() {
// US Eastern time with daylight saving rules (POSIX TZ string)
configTzTime("EST5EDT,M3.2.0,M11.1.0", "pool.ntp.org");
}
void printTime() {
struct tm now;
if (getLocalTime(&now)) {
Serial.println(&now, "%A %d %B %Y %H:%M:%S");
}
}
5 · Access-point mode
ap_mode.ino
#include <WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.softAP("ESP32-Lab", "password123"); // password: minimum 8 characters
Serial.print("Join ESP32-Lab, then open http://");
Serial.println(WiFi.softAPIP()); // usually 192.168.4.1
// ...start a WebServer as in example 2
}
void loop() {}
Wi-Fi events
WiFi.onEvent(callback) tells you about ARDUINO_EVENT_WIFI_STA_GOT_IP and
ARDUINO_EVENT_WIFI_STA_DISCONNECTED, so your code can respond without polling.
ESP-NOW
ESP-NOW is a connectionless protocol from Espressif. ESP32 boards send short messages (up to 250 bytes) directly to each other without a router. The latency is very low. It is good for remote controls and sensor networks.
OTA updates
With over-the-air updates (the ArduinoOTA library), you can upload new firmware through Wi-Fi. This is useful when the board is
installed in a project and you cannot easily get access to the USB port.
Resources
- Arduino-ESP32 Wi-Fi APIOfficial reference for modes, events and enterprise networks.
- Random Nerd Tutorials: ESP32 web serverA clear project with step-by-step instructions.
- ArduinoJsonRead and make JSON on microcontrollers. Includes an online assistant.
- Open-MeteoA free weather API that needs no key. It is good for your first HTTP projects.
- ESP-NOW documentationMessages from one device to a different device.
- Power supplies · GPIO (ADC2 note) · OLED (show the IP address on a display)Related pages.