Start the join
Wi-Fi has two roles. An access point (AP), like a home router, runs a network; a station joins one. Line 1 makes our ESP32 a station. Its radio is inside the chip, wired to a small antenna on the module.
WiFi.begin hands the network name, HomeNet, and the password to the Wi-Fi driver, then returns at once. The driver does the joining in the background, in four stages: find, join, prove, get an address.
Lines 3 to 5 ask WiFi.status() every 500 ms. While the driver works the answer is not WL_CONNECTED, so delay(500) pauses and the loop asks again. Asking over and over like this is called polling.
Four stages
The radio hops from channel to channel, 1 to 11 by default. On each it sends a probe request, “who is out there?”, and listens. On channel 6 the access point answers: HomeNet is here.
Two short exchanges follow. An authentication request and reply, then an association request and reply: the ESP32 asks to join and the access point says yes. The link exists now, but nothing is encrypted yet.
Both sides already turned password and SSID into the same 256-bit key. Four messages swap random numbers and check codes that prove it, without sending the key. Fresh encryption keys result, and WIFI_EVENT_STA_CONNECTED fires.
The link is up but the ESP32 has no IP address. Its DHCP client broadcasts Discover; the router’s DHCP server makes an Offer; Request; Ack. 192.168.1.42 is now lent to the ESP32 for a set time, a lease.
Online, and staying there
IP_EVENT_STA_GOT_IP fires and the Arduino core sets status() to WL_CONNECTED. The loop on line 3 ends and line 6 prints 192.168.1.42. Only now may the sketch open network connections.
The router reboots. WIFI_EVENT_STA_DISCONNECTED fires with a reason code and status() is no longer WL_CONNECTED. Auto-reconnect is on by default, so the core joins again. Check status() before sending, and never wait forever.
Sending, the radio draws about 240 mA; listening, 95-100 mA. Espressif recommends a 3.3 V supply giving 500 mA or more. To save energy the radio sleeps between the AP’s DTIM beacons (often every beacon): modem sleep, on by default.
What happens
;; step 1/10 · station line 1 WiFi.mode(WIFI_STA); AP runs the network: the home router station joins a network: our ESP32 (STA) board ESP32-DevKitC-32E, module ESP32-WROOM-32E radio 802.11 b/g/n, 2.4 GHz, PCB antenna
The card shows only the join inside setup(). The full sketch includes <WiFi.h>, defines ssid and pass, starts Serial at 115200 baud, and in loop() checks WiFi.status() before using the network. Real firmware also gives the while loop a timeout, so a wrong password cannot hang it forever. In the Arduino core for ESP32, status() becomes WL_CONNECTED only on the got-IP event; the link-up event (STA_CONNECTED) alone does not set it. In ESP-IDF itself it is the application’s job to call esp_wifi_connect() again after a disconnect; the Arduino core does that for you while auto-reconnect is on.