Connecting to Wi-Fi
Built-in Wi-Fi is the ESP32's headline feature, and the Arduino core for ESP32 makes joining a network
straightforward with the WiFi.h library. Remember from the
Specifications lesson that the ESP32's Wi-Fi radio is 802.11
b/g/n and operates on the 2.4GHz band only - if your ESP32 cannot see your network at
all, check that you are not looking at a 5GHz-only SSID.
Full Example: Joining a Wi-Fi Network
#include <WiFi.h>
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// your networked application logic goes here
}
Line by Line
#include <WiFi.h>- brings in the ESP32 Arduino core's Wi-Fi library.ssid/password- your network's name and password, as plain text constants.Serial.begin(115200);- starts the serial connection back to your computer so you can watch progress in the Arduino IDE's Serial Monitor.WiFi.begin(ssid, password);- tells the ESP32 to start connecting to that network. This call returns immediately - the connection happens in the background.while (WiFi.status() != WL_CONNECTED) { delay(500); ... }- repeatedly checks the connection status until it reportsWL_CONNECTED, printing a dot every half-second so you can see it is still working rather than stuck.WiFi.localIP()- once connected, returns the IP address your router assigned to the ESP32, which you will need if you want to reach the board from elsewhere on the network.
There's More to Explore: Access Point Mode
Everything above has the ESP32 joining an existing Wi-Fi network as a client (this is often
called "station mode"). The ESP32 can also do the opposite: create its own Wi-Fi network for other
devices to join, using WiFi.softAP(...). This is called Access Point (AP) mode, and it is
useful for projects where the ESP32 needs to be reachable even with no existing network around - for
example, a setup wizard that a phone connects to directly the first time a device is powered on. This
track does not walk through a full AP-mode project, but it is worth knowing the capability exists as you
explore further.
WiFi.h, call WiFi.begin(ssid, password), poll
WiFi.status() until it equals WL_CONNECTED, then read the assigned address with
WiFi.localIP(). The ESP32's Wi-Fi radio is 2.4GHz-only. It can also run in Access Point mode
via WiFi.softAP() to host its own network instead of joining one.