Learning Goals 5 min
Yesterday you saw your local WiFi networks. Today you join one. By the end of this lesson you will:
- Connect an ESP8266 / ESP32 to a known WiFi network using SSID + password from your sketch.
- Read back useful information from the connection: assigned IP address, MAC, gateway, RSSI of the active link, channel.
- Add reliable reconnection logic that survives transient drops (router reboot, signal blip, board reset) — the difference between a demo sketch and something you'd leave plugged in for weeks.
Warm-Up 10 min
Have ready: your ESP board, USB cable, your WiFi network's SSID and password. Best to use your phone's hotspot if your home/school network has heavy authentication (corporate WPA-Enterprise, captive portal).
Security note before we put a password in code
WiFi passwords in plain text inside a sketch are common in tutorials but not a great idea long-term:
- Anyone with access to your computer or GitHub repo can read it.
- If you share the sketch with classmates, your password goes with it.
For school work, use a throwaway password on your phone's hotspot rather than your main home password. For real deployments, configure WiFi via a captive portal (the user enters credentials in a browser the first time), or via a hardcoded but unique-per-device password. We'll discuss in L04.
New Concept · WiFi.begin and reconnection 25 min
The minimum viable connect
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
const char* SSID = "YourNetwork";
const char* PASSWORD = "YourPassword";
void setup() {
Serial.begin(115200);
delay(500);
Serial.println();
Serial.print("Connecting to ");
Serial.println(SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("# Connected. IP = ");
Serial.println(WiFi.localIP());
Serial.print("# RSSI = ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
}
void loop() { }Three steps:
- Mode:
WIFI_STA= station / client. - Begin: hands SSID and password to the radio. Returns immediately; connection happens in the background.
- Wait: poll
WiFi.status()until it returnsWL_CONNECTED.
What WiFi.status() returns
| Value | Meaning |
|---|---|
WL_IDLE_STATUS | Starting up; nothing happening yet. |
WL_NO_SSID_AVAIL | The SSID you asked for isn't in range. Check spelling, check range. |
WL_SCAN_COMPLETED | Scan finished (set after a scanNetworks() call). |
WL_CONNECTED | Joined and have an IP. Ready for traffic. |
WL_CONNECT_FAILED | Authentication failed (wrong password) or other handshake error. |
WL_CONNECTION_LOST | Was connected; got disconnected. |
WL_DISCONNECTED | Currently disconnected — initial state, or after a manual disconnect. |
What the assigned IP tells you
WiFi.localIP()— the IP address your router assigned via DHCP. Use this from a browser on the same network to reach the board.WiFi.gatewayIP()— your router's IP. Useful for diagnostics (ping it to confirm the route is alive).WiFi.subnetMask()— usually255.255.255.0for a home network. Tells you which IPs are "local".WiFi.macAddress()— your board's unique MAC. Useful if you want to give it a static IP reservation in your router.
Reconnection logic — production-ready
WiFi drops happen. Routers reboot. Signals fade. A polished sketch survives:
const unsigned long RECONNECT_EVERY_MS = 5000;
unsigned long lastReconnectAttempt = 0;
void ensureWiFi() {
if (WiFi.status() == WL_CONNECTED) return;
if (millis() - lastReconnectAttempt < RECONNECT_EVERY_MS) return;
lastReconnectAttempt = millis();
Serial.println("# WiFi lost; reconnecting...");
WiFi.disconnect();
WiFi.begin(SSID, PASSWORD);
}
void loop() {
ensureWiFi();
// ... your normal work here ...
}ensureWiFi() is a non-blocking re-connector. Every 5 seconds while disconnected, it tries again. While connected, it returns instantly. Drop it at the top of loop() in every WiFi sketch you write.
Static IP (optional)
DHCP gives a random-ish IP each time. For a tiny webserver you want to bookmark, configure a static IP:
IPAddress staticIP(192, 168, 1, 42);
IPAddress gateway (192, 168, 1, 1);
IPAddress subnet (255, 255, 255, 0);
WiFi.config(staticIP, gateway, subnet);
WiFi.begin(SSID, PASSWORD);Call WiFi.config() before WiFi.begin(). Make sure the static IP is outside your router's DHCP pool to avoid collisions.
Worked Example · Connect + diagnose 25 min
Step 1 — fill in your credentials
Take the §3 sketch and replace YourNetwork / YourPassword with real values (phone hotspot is easiest).
Step 2 — upload at 115200 baud
You should see:
Connecting to Mia-iPhone .... # Connected. IP = 172.20.10.3 # RSSI = -55 dBm
Three dots = three half-second polls = ~1.5 s to connect, which is normal. Cold-boot connect can take up to 10 s on a busy network.
Step 3 — full diagnostic dump
Replace the lines after "Connected" with this:
Serial.print("# SSID = ");
Serial.println(WiFi.SSID());
Serial.print("# IP = ");
Serial.println(WiFi.localIP());
Serial.print("# Gateway = ");
Serial.println(WiFi.gatewayIP());
Serial.print("# Subnet = ");
Serial.println(WiFi.subnetMask());
Serial.print("# DNS = ");
Serial.println(WiFi.dnsIP());
Serial.print("# MAC = ");
Serial.println(WiFi.macAddress());
Serial.print("# RSSI = ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
Serial.print("# Channel = ");
Serial.println(WiFi.channel());This is your "network info" banner. Print it once at boot in every WiFi sketch — gives you all the diagnostic context you need when things go wrong.
Step 4 — ping the board from your laptop
On the same network, open a terminal and run ping 172.20.10.3 (replace with your board's IP). You should see replies every second. The board is now a real network device — your laptop can find it by IP.
Step 5 — test reconnection
Add the ensureWiFi() helper from §3 to loop(). Then while the sketch is running, briefly turn off your phone's hotspot. The board prints "# WiFi lost; reconnecting...". Re-enable the hotspot. The board reconnects automatically.
Step 6 — measure typical link quality at different distances
Put the ESP next to the router; note the RSSI (probably −30 dBm). Move 5 m through one wall; note again (probably −55 dBm). 10 m through two walls; probably −75 dBm. This is the data you need to plan where in your house a WiFi-powered project will actually work.
Basic 5 min
Goal: Print the connection time in milliseconds. (How long did WiFi.begin + waiting take?)
Challenge 1 5 min
Goal: Add a timeout to the connect loop. If 30 seconds pass without connecting, print "# Connect timed out" and try to reconnect later. Don't block forever.
Challenge 2 5 min
Goal: Try connecting to two networks in priority order: prefer home WiFi, fall back to phone hotspot if home is unreachable. Print which one you ended up on.
Challenge 3 · Build a connection logger 10 min
Polish your sketch so it's a usable diagnostic tool for any future WiFi project.
- Boot banner: SSID, IP, RSSI, MAC.
- In
loop(), every 30 seconds: print one line with current RSSI and connection status. - When disconnected: print one line per reconnect attempt.
- When reconnected: print "# Reconnected after Xs (Y attempts)".
Save as wifi-diag.ino. First sketch to upload whenever a future project has connectivity problems — it tells you whether the issue is WiFi or higher up the stack (DNS, server, etc.).
Recap 5 min
WiFi.begin(SSID, password) + poll WiFi.status() == WL_CONNECTED = connected. Read the IP, gateway, RSSI, channel for diagnostics. Add a non-blocking ensureWiFi() at the top of loop() so the device survives router reboots and signal blips. Phone hotspot is the safest network for school work — no password leakage if you share code. 5 GHz isn't supported; corporate WPA-Enterprise isn't supported. Tomorrow we use the connection to actually fetch a web page — your first HTTP client.
- SSID
- Service Set Identifier — the human-readable network name ("Home-WiFi").
- Station mode / Access Point mode
- STA = client connecting to an existing router. AP = the board IS a router.
WiFi.mode()selects. - DHCP
- Dynamic Host Configuration Protocol — the router assigns an IP to each new device. The default; gives you a different IP each time.
- Static IP
- An IP you manually configure on the device, outside the router's DHCP pool. Lets you bookmark
http://192.168.1.42reliably. - Gateway
- Your router's IP. The device sends all non-local traffic here.
- MAC address
- The board's unique 48-bit hardware ID. Used for DHCP reservations and some network ACLs.
- RSSI
- Signal strength in dBm. −30 dBm = excellent, −85 dBm = barely usable.
- Reconnect logic
- Code that automatically rejoins WiFi after a drop. Required for any unattended device.
- WiFi.status()
- Returns the current state of the WiFi state machine. Poll for
WL_CONNECTED; switch on the others for diagnostics. - WiFiMulti
- Helper that picks the strongest of several known networks.
ESP8266WiFiMultion ESP8266;WiFiMultion ESP32.
Extra Mission 5 min
Part 1 — Design a status light for a connected device
Smart speakers and routers use one small light to tell you how their connection is doing. Pick a device that needs WiFi — a doorbell, a weather station, a plant sensor. On paper, design its status light.
Your design must include:
- A different light pattern for each state: connecting, connected, signal weak, connection lost.
- The RSSI value where "connected" becomes "signal weak".
- Which
WiFi.status()values lead to each pattern. - Which pin each LED uses (one LED or an RGB LED).
Part 2 — Make it
Add your status light to wifi-diag.ino. Use millis() for every blink pattern, so ensureWiFi() still runs on every pass of loop(). Test it by turning your phone hotspot off and on, and by walking away from the router.
Bring back next class: your design, your uploaded sketch, and a Serial Monitor screenshot showing a drop and a reconnect.