Connect ESP32 to Wi-Fi in Station Mode With esp_wifi
Connect an ESP32 to Wi-Fi in station mode with ESP-IDF v5.4: set up netif and the event loop, handle STA events, retry and wait for an IP.

Connecting an ESP32 to a Wi-Fi network takes about twenty lines in the Arduino core and about sixty in ESP-IDF. The longer version is not ceremony: each piece corresponds to a layer that you will need to control later, such as the network interface, the event loop that delivers connection state, and the driver itself. This post builds a station-mode connection step by step for ESP-IDF v5.4, explains why the code is ordered the way it is, shows the log of a successful and a failed attempt, and covers retrying and reading the signal strength. The code uses WPA2 credentials stored in constants for the example, which a product should replace with stored or provisioned credentials.
Station mode, abbreviated STA, means the ESP32 is a client of an existing access point, like a phone or a laptop. The other main mode, access point mode, makes the chip host its own network, and a third mode runs both at once.
The layers you are initializing
Wi-Fi in ESP-IDF is not one library but four cooperating pieces, and the initialization calls name them:
NVS, the non-volatile storage, because the Wi-Fi driver keeps calibration data there.
**
esp_netif**, the abstraction that binds a network interface to the TCP/IP stack (lwIP). It owns IP addresses, DHCP and DNS.The default event loop, which delivers
WIFI_EVENTandIP_EVENTnotifications to your handlers.**
esp_wifi**, the driver, with its own task, which scans, authenticates and associates.
The calls go in a fixed order because each layer needs the one before it. If you skip nvs_flash_init(), esp_wifi_init() returns an error about storage. If you register handlers before the event loop exists, registration fails.
The full program
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "nvs_flash.h"
#define WIFI_SSID "example-network"
#define WIFI_PASSWORD "change-me-please"
#define MAX_RETRIES 5
#define CONNECTED_BIT BIT0
#define FAILED_BIT BIT1
static const char *TAG = "wifi_sta";
static EventGroupHandle_t s_wifi_events;
static int s_retries;
static void wifi_event_handler(void *arg, esp_event_base_t base,
int32_t id, void *data)
{
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
wifi_event_sta_disconnected_t *d = (wifi_event_sta_disconnected_t *)data;
if (s_retries < MAX_RETRIES) {
s_retries++;
ESP_LOGW(TAG, "disconnected (reason %d), retry %d/%d",
d->reason, s_retries, MAX_RETRIES);
esp_wifi_connect();
} else {
xEventGroupSetBits(s_wifi_events, FAILED_BIT);
}
} else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
ESP_LOGI(TAG, "got ip " IPSTR, IP2STR(&e->ip_info.ip));
s_retries = 0;
xEventGroupSetBits(s_wifi_events, CONNECTED_BIT);
}
}
static esp_err_t wifi_connect_blocking(void)
{
s_wifi_events = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&init));
esp_event_handler_instance_t h_wifi, h_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(
WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, &h_wifi));
ESP_ERROR_CHECK(esp_event_handler_instance_register(
IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, &h_ip));
wifi_config_t cfg = { 0 };
strlcpy((char *)cfg.sta.ssid, WIFI_SSID, sizeof(cfg.sta.ssid));
strlcpy((char *)cfg.sta.password, WIFI_PASSWORD, sizeof(cfg.sta.password));
cfg.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &cfg));
ESP_ERROR_CHECK(esp_wifi_start());
EventBits_t bits = xEventGroupWaitBits(s_wifi_events,
CONNECTED_BIT | FAILED_BIT,
pdFALSE, pdFALSE, portMAX_DELAY);
return (bits & CONNECTED_BIT) ? ESP_OK : ESP_FAIL;
}
void app_main(void)
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
if (wifi_connect_blocking() == ESP_OK) {
ESP_LOGI(TAG, "connected");
} else {
ESP_LOGE(TAG, "could not connect");
}
}The project needs the esp_wifi, esp_event, esp_netif and nvs_flash components, which main already reaches in ESP-IDF v5.4 through its default requirements. If you hit a missing header, add them to PRIV_REQUIRES in main/CMakeLists.txt.
What happens, in order
Calling esp_wifi_start() starts the driver and raises WIFI_EVENT_STA_START. The handler responds by calling esp_wifi_connect(), which scans for the SSID, authenticates and associates. A link-level success raises WIFI_EVENT_STA_CONNECTED, which the example ignores. At that point the device has a link but no IP address, so it cannot use the network. DHCP then runs inside the TCP/IP stack, and on success IP_EVENT_STA_GOT_IP fires with the address. Only then does the code set CONNECTED_BIT.
This distinction is the most common source of beginner bugs: starting a socket as soon as the link is up fails because there is no address yet. Wait for the IP event, which is what the event group does, and app_main unblocks only when the network is usable.
A successful run prints, with different addresses and timestamps on your network:
I (645) wifi:new:<6,0>, old:<1,0>, ap:<255,255>, sta:<6,0>, prof:1, snd_ch_cfg:0x0
I (645) wifi:state: init -> auth (0xb0)
I (655) wifi:state: auth -> assoc (0x0)
I (665) wifi:state: assoc -> run (0x10)
I (695) wifi:connected with example-network, aid = 1, channel 6, BW20, bssid = 3c:84:6a:00:00:01
I (1735) esp_netif_handlers: sta ip: 192.168.1.42, mask: 255.255.255.0, gw: 192.168.1.1
I (1735) wifi_sta: got ip 192.168.1.42
I (1735) wifi_sta: connectedThe wifi: lines come from the driver's own log tag and show the state machine moving from auth to assoc to run. The line from the example is got ip.
Reading a failure
With a wrong password, the driver cannot complete the four-way handshake and the access point disconnects the station. The handler logs the reason code, then retries:
W (2105) wifi_sta: disconnected (reason 15), retry 1/5
W (4215) wifi_sta: disconnected (reason 15), retry 2/5
W (6325) wifi_sta: disconnected (reason 15), retry 3/5
W (8435) wifi_sta: disconnected (reason 15), retry 4/5
W (10545) wifi_sta: disconnected (reason 15), retry 5/5
E (10545) wifi_sta: could not connectReason 15 is WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT, the code you most often see for a wrong passphrase. Other common reasons are 201, WIFI_REASON_NO_AP_FOUND, when the SSID is not visible on any channel the chip scans, and 202, WIFI_REASON_AUTH_FAIL. The full list is the wifi_err_reason_t enumeration in esp_wifi_types.h. Logging the numeric reason, as the handler does, turns a vague "it will not connect" into a specific cause.
The retry limit matters. Reconnecting forever with no delay hammers a busy access point and drains a battery; a bounded count with a growing delay is the usual policy.
Choosing the security threshold
cfg.sta.threshold.authmode is the minimum security the station will accept. Setting WIFI_AUTH_WPA2_PSK means the station will connect to WPA2 and stronger networks, and refuse open and WEP ones. Leaving it at the default of zero allows an open network, which is why a station can silently join a rogue open network with the same SSID. For a network that uses WPA3-SAE, set cfg.sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH and use WIFI_AUTH_WPA2_WPA3_PSK as the threshold, so the chip can connect to both a WPA3 and a WPA2 transition-mode network.
Signal strength and the connected network
After a connection, esp_wifi_sta_get_ap_info() returns the access point record, including the RSSI in dBm and the channel:
wifi_ap_record_t ap;
if (esp_wifi_sta_get_ap_info(&ap) == ESP_OK) {
ESP_LOGI(TAG, "ssid %s channel %d rssi %d", ap.ssid, ap.primary, ap.rssi);
}I (1745) wifi_sta: ssid example-network channel 6 rssi -52RSSI is negative, and a value closer to zero is stronger. As a rule of thumb from vendor documentation, values worse than around -80 dBm give an unreliable link, but the threshold depends on the data rate and the environment, so measure on the board and in the enclosure you will ship.
Do not hard-code credentials
The example embeds the SSID and passphrase in the firmware, which is acceptable for a bench test and wrong for a product. Anyone who dumps the flash reads them, and the device cannot move to another network. Better options are provisioning over BLE or a temporary access point with the wifi_provisioning component, or storing credentials in NVS after the first configuration and reading them back at boot. When a configuration has been stored, esp_wifi_set_storage(WIFI_STORAGE_FLASH) makes the driver restore it itself.
Handling a changing network
A device on a desk sees the same access point for weeks, and a device in a building sees it vanish, reboot and come back. The retry logic above gives up after five attempts, which is right for start-up and wrong for a connection that should last. After the first success, replace the counter with a policy that never gives up but waits longer each time:
static void schedule_reconnect(int attempt)
{
int delay_ms = 1000 << (attempt < 6 ? attempt : 6); /* 1 s up to 64 s */
vTaskDelay(pdMS_TO_TICKS(delay_ms));
esp_wifi_connect();
}Calling vTaskDelay inside an event handler blocks the default event loop task, which also delivers IP and other events to your application. A better design posts a message to a worker task, or starts a one-shot esp_timer that calls esp_wifi_connect() when it fires. The key point is that handlers on the default loop must return quickly, and a sleeping handler delays every other subscriber.
Also decide what the rest of the firmware does while the network is gone. A sensor node should keep sampling and buffer readings, and a controller should fall back to a safe state. The connected event group in the example lets other tasks wait for the network with a timeout instead of blocking forever, using xEventGroupWaitBits with a finite tick count.


