Beginner · Lesson 6 of 10

Wi-Fi and your first request

Join a 2.4 or 5 GHz network on the ESP32-C5 with ESP-IDF v6.1.1, reconnect with jittered back-off, keep credentials out of git and make an HTTP request to your own computer.

BeginnerEspressif45 minUpdated 28 November 2026Tier 1: Builds in CI

You will learn

  • Join a Wi-Fi network from ESP-IDF and choose 2.4 GHz, 5 GHz or automatic band selection on the ESP32-C5
  • Reconnect after a drop with exponential back-off and random jitter, without blocking the event loop
  • Keep Wi-Fi credentials in a gitignored file while the project still builds in CI
  • Make an HTTP GET request to a server on your own network and read the reply

Before this: A sensor over I²C

So far your board has talked to sensors on its own bench. This lesson puts it on your network. You will join a Wi-Fi access point (AP) from ESP-IDF on the ESP32-C5, pick the radio band, recover from dropped connections without hammering the AP, and fetch a web page from your own computer. The code is a complete ESP-IDF project in examples/l06-wifi-request/, built in CI with ESP-IDF v6.1.1.

What you need

  • An ESP32-C5-DevKitC-1 or another ESP32-C5 board, and the USB cable from lesson 3.
  • ESP-IDF v6.1.1. It is a bug-fix release of v6.1, published on 16 November 2026. Espressif’s compatibility table lists the ESP32-C5 as supported from ESP-IDF v5.5.2, so v6.1.1 covers it.
  • A Wi-Fi network you control, using WPA2 or WPA3, and a computer on the same network with Python 3.

Two bands, one radio

The ESP32-C5 has a single 2.4 and 5 GHz Wi-Fi 6 (IEEE 802.11ax) radio with one transmit and one receive chain (1T1R in the datasheet). Its datasheet (v1.5, an official release for parts in mass production) lists centre frequencies of 2412 to 2484 MHz on 2.4 GHz and 5180 to 5885 MHz on 5 GHz. Which of those channels you may use depends on where you are. ESP-IDF sets the allowed channels with esp_wifi_set_country(), and its guide notes that the 5 GHz radar-detection (DFS) channels vary by country or region.

ESP-IDF v6.1.1 exposes band selection through one call, esp_wifi_set_band_mode():

Mode What the station does
WIFI_BAND_MODE_2G_ONLY Scans and connects on 2.4 GHz channels only
WIFI_BAND_MODE_5G_ONLY Scans and connects on 5 GHz channels only
WIFI_BAND_MODE_AUTO Picks the band from the AP it connects to

Two details trip people up. First, AUTO is not simultaneous dual-band operation. The ESP-IDF guide is explicit that it only allows automatic band selection. The radio is on one band at a time. Second, when your router broadcasts the same network name on both bands, the driver prefers the 5 GHz AP if its signal is within rssi_5g_adjustment dB of the 2.4 GHz one. The default is 10 dB. Raise it to favour 5 GHz more, or lower it to favour the stronger signal.

The bands also differ in current. In the datasheet’s active-mode tables (3.3 V, 25 °C), receiving costs 87 mA on 2.4 GHz (802.11b/g/n, 20 MHz) and 110 mA on 5 GHz (802.11a/n, 20 MHz). Peak transmit current is 320 mA for 802.11b at 20 dBm and 408 mA for 802.11a at 18 dBm. These are chip figures at different data rates and output powers, so treat them as a hint, not a ranking. Which band gives the better link in your building is something to measure. Our method for that is /lab/methods/throughput-and-range/.

In AUTO mode, the single-band calls esp_wifi_set_protocol() and esp_wifi_set_bandwidth() return ESP_ERR_NOT_SUPPORTED. Use the plural forms, esp_wifi_set_protocols() and esp_wifi_set_bandwidths(), which take one setting per band.

Keeping credentials out of the code

A Wi-Fi password committed to a public repository stays in its history even after you delete the line. The rule on this site is that credentials live in a file that git ignores, and the repository holds an example with placeholders:

// target: esp32c5 sdk: esp-idf tier: 1 (built in CI in place of secrets.h)
// Copy this file to secrets.h (same folder) and fill in your values.
// secrets.h is listed in .gitignore, so it never reaches the repository.
#pragma once

#define WIFI_SSID     "your-network-name"
#define WIFI_PASSWORD "your-network-password"

// A plain HTTP server on your own network, for example `python3 -m http.server 8000`
// run on your computer. Replace the address with your computer's IP address.
#define REQUEST_URL   "http://192.168.1.50:8000/"

You copy it to main/secrets.h and fill in your values. The example’s .gitignore lists main/secrets.h, so git status never shows it. The firmware includes the real file when it exists and falls back to the example otherwise:

// target: esp32c5 sdk: esp-idf tier: 1
// examples/l06-wifi-request/main/app_main.c (excerpt)
#if __has_include("secrets.h")
#include "secrets.h"
#define HAVE_SECRETS 1
#else
#include "secrets.h.example"  // placeholders, so the project still builds in CI
#define HAVE_SECRETS 0
#endif

The fallback matters for CI. Our build server has no secrets, yet it compiles and links the whole Wi-Fi path with placeholder values. An earlier version of this example skipped Wi-Fi when the file was missing, and the compiler then removed the Wi-Fi stack altogether, so the build “passed” without testing anything. At run time, HAVE_SECRETS triggers a warning in the log.

The other common pattern is a Kconfig.projbuild menu, so the SSID and password are set in idf.py menuconfig. That works, but the values land in the sdkconfig file in your project folder, so sdkconfig must be gitignored too. This example uses menuconfig only for settings that are not secret: the band mode and the longest back-off wait.

Keep one more fact in mind. With ESP-IDF’s default settings, the station configuration you pass to esp_wifi_set_config() is also stored in the chip’s non-volatile storage (NVS) flash partition and reused at the next boot. The password is out of git, but it is on the device. That is a product question, covered in the lanes below.

The connection sequence

esp_wifi_start()set band modeesp_wifi_connect()connectedGET every 30 swait 1, 2, 4 … 60 splus up to 50 % jitterGOT_IPSTA_DISCONNECTEDfailstimer fires
How the lesson 6 firmware joins Wi-Fi and stays connected. A failed attempt or a dropped connection starts a one-shot back-off timer, and the timer callback calls esp_wifi_connect() again. A new IP address resets the back-off.

ESP-IDF’s Wi-Fi driver runs in its own task and reports progress as events on the default event loop. Your code registers handlers for the events it cares about and never waits inside them. Here is the start-up sequence:

// target: esp32c5 sdk: esp-idf tier: 1
// examples/l06-wifi-request/main/app_main.c (excerpt)
static void wifi_start(void)
{
    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_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, on_event, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_event, NULL));

    const esp_timer_create_args_t t = {.callback = retry_cb, .name = "wifi_retry"};
    ESP_ERROR_CHECK(esp_timer_create(&t, &s_retry_timer));

    wifi_config_t cfg = {0};
    strncpy((char *)cfg.sta.ssid, WIFI_SSID, sizeof(cfg.sta.ssid));
    strncpy((char *)cfg.sta.password, WIFI_PASSWORD, sizeof(cfg.sta.password));
    cfg.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;  // refuse open and WEP networks
    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());

#if SOC_WIFI_SUPPORT_5G
    // Band mode can only be set after esp_wifi_start().
#if CONFIG_L06_BAND_2G
    ESP_ERROR_CHECK(esp_wifi_set_band_mode(WIFI_BAND_MODE_2G_ONLY));
#elif CONFIG_L06_BAND_5G
    ESP_ERROR_CHECK(esp_wifi_set_band_mode(WIFI_BAND_MODE_5G_ONLY));
#else
    ESP_ERROR_CHECK(esp_wifi_set_band_mode(WIFI_BAND_MODE_AUTO));
#endif
#endif
    esp_wifi_connect();
}

Three lines deserve a comment. threshold.authmode = WIFI_AUTH_WPA2_PSK sets the weakest security the station accepts. ESP-IDF would default to WPA2 anyway when the password is WPA2-length, but writing it down makes the intent clear. esp_wifi_set_band_mode() comes after esp_wifi_start() because, according to esp_wifi.h in v6.1.1, it returns ESP_ERR_WIFI_NOT_STARTED before that. The #if SOC_WIFI_SUPPORT_5G guard keeps the file building for single-band chips. Finally, nvs_flash_init() runs first in app_main() because the driver keeps its settings and its radio calibration data in NVS.

Reconnect with back-off

Connections drop. The AP reboots for a firmware update, someone switches off a mesh node, or the sensor sits at the edge of coverage. A naive handler calls esp_wifi_connect() again the moment it sees a disconnect. If the AP is down for a minute, the device makes hundreds of attempts, each one a burst of transmit current. If you have 30 sensors, they all retry in lock-step the instant the AP comes back.

Exponential back-off with jitter fixes both problems. Each failure doubles the wait, up to a ceiling, and a random extra spreads devices out in time:

// target: esp32c5 sdk: esp-idf tier: 1
// examples/l06-wifi-request/main/app_main.c (excerpt)
// Exponential back-off: 1 s, 2 s, 4 s ... capped at CONFIG_L06_BACKOFF_MAX_S,
// plus up to 50 % random jitter so many devices do not retry in step.
static uint64_t backoff_us(uint32_t attempt)
{
    uint64_t base_s = 1ULL << (attempt < 16 ? attempt : 16);
    if (base_s > CONFIG_L06_BACKOFF_MAX_S) {
        base_s = CONFIG_L06_BACKOFF_MAX_S;
    }
    uint64_t us = base_s * 1000000ULL;
    return us + (esp_random() % (us / 2 + 1));
}

static void retry_cb(void *arg)
{
    ESP_LOGI(TAG, "reconnect attempt %" PRIu32, s_attempt);
    esp_wifi_connect();
}

static void on_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
    if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
        const wifi_event_sta_disconnected_t *d = data;
        xEventGroupClearBits(s_events, GOT_IP_BIT);
        uint64_t wait = backoff_us(s_attempt++);
        ESP_LOGW(TAG, "disconnected, reason %u, rssi %d dBm, retry in %" PRIu64 " ms",
                 d->reason, d->rssi, wait / 1000);
        esp_timer_stop(s_retry_timer);  // harmless if it was not running
        esp_timer_start_once(s_retry_timer, wait);
    } else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
        const ip_event_got_ip_t *e = data;
        wifi_ap_record_t ap;
        wifi_band_t band = WIFI_BAND_2G;
        esp_wifi_sta_get_ap_info(&ap);
        esp_wifi_get_band(&band);
        ESP_LOGI(TAG, "got " IPSTR " on channel %u (%s GHz), rssi %d dBm", IP2STR(&e->ip_info.ip),
                 ap.primary, band == WIFI_BAND_5G ? "5" : "2.4", ap.rssi);
        s_attempt = 0;
        xEventGroupSetBits(s_events, GOT_IP_BIT);
    }
}

The disconnect handler never sleeps. It starts a one-shot esp_timer, and the timer’s callback calls esp_wifi_connect(). Blocking inside an event handler would stall every other event on the default loop, including the one that tells you the IP address arrived. On IP_EVENT_STA_GOT_IP the attempt counter resets, so the next drop starts again at about 1 s.

The disconnect event carries a reason code and the last signal strength (RSSI). Log both. Reason codes are defined in esp_wifi_types_generic.h, and they tell a wrong password apart from an AP that has gone away. The connected log line also reports the channel and band, which is how you check what AUTO mode chose.

Your first request

Start a web server on your computer, in any folder:

python3 -m http.server 8000

Find the computer’s IP address on your network, put http://<that address>:8000/ in REQUEST_URL in secrets.h, then build and flash:

cd examples/l06-wifi-request
cp main/secrets.h.example main/secrets.h   # then edit it
idf.py set-target esp32c5
idf.py menuconfig                          # optional: "Lesson 6 settings" for band and back-off
idf.py build flash monitor

The request itself uses ESP-IDF’s HTTP client in its open, fetch headers, read and close form, which keeps the code short and shows each step:

// target: esp32c5 sdk: esp-idf tier: 1
// examples/l06-wifi-request/main/app_main.c (excerpt)
static void http_get_once(void)
{
    esp_http_client_config_t cfg = {.url = REQUEST_URL, .timeout_ms = 5000};
    esp_http_client_handle_t c = esp_http_client_init(&cfg);
    if (esp_http_client_open(c, 0) != ESP_OK) {
        ESP_LOGE(TAG, "could not connect to %s", REQUEST_URL);
        esp_http_client_cleanup(c);
        return;
    }
    int64_t len = esp_http_client_fetch_headers(c);
    char buf[129] = {0};
    int n = esp_http_client_read(c, buf, sizeof(buf) - 1);
    ESP_LOGI(TAG, "GET %s -> HTTP %d, content-length %" PRId64 ", first %d bytes:\n%s",
             REQUEST_URL, esp_http_client_get_status_code(c), len, n > 0 ? n : 0, buf);
    esp_http_client_close(c);
    esp_http_client_cleanup(c);
}

When it works, the serial monitor shows the IP address, channel and band, then HTTP 200 and the first lines of the directory listing your computer served. The computer’s terminal logs the same request. Stop the Python server and you will see could not connect every 30 s while Wi-Fi itself stays up. Switch off your AP and you will see the back-off waits grow.

This is plain HTTP on your own network, which is fine for learning. Anything that leaves your network, or carries credentials, needs TLS and certificate checks.

One build note: Wi-Fi plus the HTTP client produced an application image of 0x103400 bytes in our build, just over the 1 MB app partition of ESP-IDF’s default partition table. The example’s sdkconfig.defaults selects the larger single-app table (CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE) so the build fits.

For makers

Use AUTO mode unless you have a reason not to, and read the connected log line to see which band you got. Keep secrets.h out of git and back it up somewhere private. If the board sits far from the router, try 2.4 GHz only and compare the logged RSSI. Leave the back-off ceiling at 60 s: a sensor that rejoins within a minute of the router coming back is good enough at home.

For product teams

Compiled-in credentials do not scale past one network. Production devices receive Wi-Fi details at commissioning, from a phone app over Bluetooth LE or a temporary access point, and keep them in NVS. Plan flash encryption and NVS encryption before the first unit ships. Decide the band policy per market and test it against the APs your customers use. Keep jittered back-off with a ceiling: a fleet that retries in step after an outage looks like a flood to the network. Log disconnect reasons to your device telemetry, because they are the first thing support will ask for.

Exercise

  1. Set the band mode to 5 GHz only in menuconfig. If your router has no 5 GHz network, check the log to see what the device does and how the back-off grows.
  2. Change CONFIG_L06_BACKOFF_MAX_S to 10 and switch your AP off for two minutes. Count the reconnect attempts in the log, then repeat with the default of 60 s.
  3. Point REQUEST_URL at a file you create in the server’s folder, for example hello.txt, and print its contents.

Summary

  • The ESP32-C5 has one 1T1R radio for 2.4 and 5 GHz. In ESP-IDF v6.1.1, esp_wifi_set_band_mode() picks 2.4 GHz only, 5 GHz only or AUTO, and AUTO means automatic choice, not both at once.
  • Call esp_wifi_set_band_mode() after esp_wifi_start(), and use the plural protocol and bandwidth calls in AUTO mode.
  • Reconnect from a timer, not from inside the event handler, with exponential back-off, a ceiling and random jitter.
  • Credentials go in a gitignored secrets.h with a committed example. With default settings they are also stored in NVS on the device.
  • A plain HTTP GET to your own computer proves the whole path from radio to application.

Further reading