Wi-Fi for embedded
Station and AP modes, provisioning, power save and security.
Fast, everywhere, and power-hungry
Wi-Fi (IEEE 802.11) gives a device direct IP connectivity through infrastructure the customer already has. It carries megabits easily, so it suits cameras, appliances, displays, audio and anything mains-powered that talks to the cloud. Its cost is power: transmitting draws 100 to 300 mA, and staying connected costs milliamps on average without careful power-save configuration.
Common embedded parts: ESP32 family (Wi-Fi + BLE SoC), Infineon/Cypress CYW43 (Raspberry Pi Pico W), NXP, Realtek, Silicon Labs, and Wi-Fi modules controlled over SPI, SDIO or AT commands.
Standards in brief
| Standard | Marketing name | Band | Notes for embedded |
|---|---|---|---|
| 802.11b/g | — | 2.4 GHz | Legacy; still the baseline for compatibility |
| 802.11n | Wi-Fi 4 | 2.4 / 5 GHz | Most IoT modules |
| 802.11ac | Wi-Fi 5 | 5 GHz | Higher throughput |
| 802.11ax | Wi-Fi 6 / 6E | 2.4 / 5 / 6 GHz | Target Wake Time for scheduled low-power wake-ups |
| 802.11ah | Wi-Fi HaLow | Sub-1 GHz | Long range, low power; niche |
2.4 GHz has better range and wall penetration and is what most IoT modules support; it is also crowded (Bluetooth, microwave ovens, neighbours' networks).
Station mode and access point mode
| Mode | The device | Used for |
|---|---|---|
| Station (STA) | Joins an existing network, like a laptop | Normal operation |
| Access point (AP / SoftAP) | Creates its own network; phones connect to it | Initial set-up, local control without a router |
| AP + STA | Both at once | Set-up while trying to join, mesh-like bridging |
Connecting as a station
- Scan for networks (or go straight to a known one on a known channel).
- Authenticate and associate with the access point.
- Four-way handshake (WPA2/WPA3) to derive encryption keys from the password.
- DHCP to get an IP address, gateway and DNS server.
- Application connection: DNS lookup, TCP, TLS.
Each step can fail separately; log which one, because the fixes differ (wrong password versus DHCP server full versus DNS blocked).
Speed-ups for devices that reconnect often: cache the channel and BSSID, use a static IP or reuse the previous DHCP lease, and resume TLS sessions.
Provisioning: getting credentials onto a headless device
A device with no screen must learn the user's network name and password. Common methods:
| Method | How | Trade-offs |
|---|---|---|
| SoftAP + web page | Device starts an AP; the user connects a phone and enters credentials in a captive web page | Works with any phone; clunky user experience |
| BLE provisioning | A phone app sends credentials over BLE | Smooth; needs BLE and an app; the common modern choice |
| SmartConfig / multicast tricks | Phone encodes credentials in packet lengths on the network | Fragile; deprecated |
| QR code / NFC / WPS | Various | WPS has known security flaws; avoid |
| Matter commissioning | Standardised, BLE-based | For smart-home devices |
| Factory or cloud-provisioned | For enterprise deployments | — |
Whatever the method, encrypt the credentials in transit (ESP-IDF's provisioning uses a proof-of-possession key), store them protected, and provide a way to reset to provisioning mode (a long button press).
Security
- WPA2-Personal (PSK): password-based; vulnerable to offline guessing if the password is weak.
- WPA3-Personal (SAE): resistant to offline dictionary attacks, forward secrecy; support it where the chip does, with WPA2 fallback ("transition mode").
- WPA2/WPA3-Enterprise (802.1X, EAP-TLS): per-device certificates against a RADIUS server; needed for corporate networks.
- Never use WEP or open networks for anything sensitive; protect application traffic with TLS regardless, since Wi-Fi encryption only covers the first hop.
Power management
| Technique | Mechanism | Effect |
|---|---|---|
| Power-save mode (DTIM sleep) | The station tells the AP it sleeps; the AP buffers packets and announces them in beacons. The station wakes for beacons (every DTIM interval, e.g. 100 to 300 ms) | Stays connected at a few mA average |
| Listen interval | Wake for every Nth DTIM beacon | Lower power, higher downlink latency |
| Deep sleep + reconnect | Turn Wi-Fi off between reports | Lowest sleep current; reconnect costs 1 to 3 s at high current |
| Target Wake Time (Wi-Fi 6) | Negotiate exact wake schedules with the AP | Long sleeps while staying associated |
The right choice depends on how often data is sent and whether the device must receive unsolicited messages. A device sending every 10 minutes is usually better off fully off between reports; a smart plug that must respond instantly stays associated in power-save mode.
#include <stdio.h>
int main(void) {
/* Compare: stay associated in power-save, or deep sleep and reconnect each time. */
double ps_avg_ma = 1.2; /* associated, DTIM sleep */
double reconnect_mas = 2.0 * 120.0; /* 2 s at 120 mA to rejoin and send */
double sleep_ma = 0.02;
int periods_s[] = { 10, 60, 600, 3600 };
for (int i = 0; i < 4; i++) {
double p = periods_s[i];
double deep = (reconnect_mas + sleep_ma * (p - 2.0)) / p;
printf("report every %4d s: stay associated %.2f mA, reconnect each time %.2f mA -> %s\n",
periods_s[i], ps_avg_ma, deep, deep < ps_avg_ma ? "reconnect" : "stay associated");
}
return 0;
}
Robustness
- Reconnect automatically with backoff after the AP disappears or the password changes; never give up permanently.
- Handle the router rebooting, DHCP leases expiring and IP addresses changing.
- Check RSSI and log it with errors: many "bugs" are weak signal.
- Coexistence: on combined Wi-Fi + BLE chips, the radios share an antenna and time-slice; heavy Wi-Fi traffic reduces BLE performance and vice versa.
Pitfall: Many routers' 2.4 GHz and 5 GHz networks share one name. A 2.4 GHz-only device then sometimes fails to join because the phone used to provision it was on 5 GHz. Tell users, or detect and explain the failure.
Interview question: How would you provision Wi-Fi credentials onto a device with no screen?
Answer: The common modern approach is BLE provisioning: on first boot or after a reset gesture, the device advertises over BLE, a companion app connects, establishes an encrypted session (with a proof-of-possession code printed on the device), scans for or accepts the network name and password, and the device tries to join and reports success or the exact failure back over BLE. The alternative is SoftAP with a captive web page. Store credentials protected, provide a factory reset, and handle 2.4 versus 5 GHz confusion.
Interview question: A Wi-Fi sensor reports every 15 minutes. Should it stay connected or reconnect each time?
Answer: Usually reconnect each time: staying associated in power-save mode costs around a milliamp or more continuously, while a full reconnect costs one to three seconds at around 100 mA, which averaged over 15 minutes is much less. Shorten reconnects by caching the channel and BSSID, reusing the IP lease, and resuming TLS sessions. Stay connected only if the device must receive messages promptly or reports very frequently; measure both on the real network to confirm.
Build it: join the depot's Wi-Fi, and only the depot's
This is step 3 of the module project, the shipping-container tracker tag. In the depot, the tag uploads its log of the journey over Wi-Fi, which is cheaper than cellular for a few hundred kilobytes. The depot has several access points with the same network name, a café next door, and, sooner or later, someone who sets up an open network with the depot's name to see what devices join it.
Lab: Pick the access point, and decide when to roam
ap_pick(scan, n, known, nk, avoid, navoid)returns the index inscanof the access point to join, or -1. An access point qualifies when:- its SSID equals a known network's SSID exactly (SSIDs are case-sensitive);
- its security is at least what that network was set up with (
SEC_OPEN<SEC_WPA2<SEC_WPA3), so an open network wearing the depot's name is never joined; - its BSSID (the access point's own address) is not in
avoid, the access points that refused the tag recently; - its signal is at least
MIN_RSSI; weaker links drop and retry, which costs more than they save.
Of those, take the strongest signal; at equal strength prefer 5 GHz (a channel above 14), which is usually less crowded.
should_roam(cur, best)returns 1 when the tag should move from its current access point to the best one seen: only when the current signal is below -70 dBm and the other is at least 8 dB stronger. Without that margin a tag between two access points hops back and forth.
Going deeper
Interview question: How would you make a smart plug stay connected through router reboots?
Answer: Detect disconnection quickly, reconnect with backoff, and keep local control working without the cloud. Re-establish the cloud connection and resubscribe after reconnecting, provision credentials securely, and use Wi-Fi power-save modes when idle. Test with router reboots and weak signal.
Interview question: What does the DTIM interval do and how does it affect battery life?
Answer: Access points send beacons regularly, and every DTIM-th beacon announces buffered broadcast and multicast traffic and which sleeping stations have unicast data waiting. A station in power-save mode can sleep between DTIM beacons; a larger DTIM interval (set on the AP) or listen interval (requested by the station) lets it sleep longer and save power, at the cost of higher latency for incoming traffic.
Interview question: Why is Wi-Fi coexistence with BLE a problem on combo chips?
Answer: Both use the 2.4 GHz band and typically share one radio and antenna on combo chips, so they must time-share: the coexistence arbiter grants the radio to one at a time based on priorities. Heavy Wi-Fi traffic can starve BLE connection events (causing disconnections or slow throughput) and vice versa. Tuning coexistence priorities, BLE connection intervals and Wi-Fi power-save helps.
Explain it: In your own words, explain the steps a Wi-Fi device goes through to send its first message after waking.
Answer: It scans for or goes directly to the known access point, authenticates and associates with it, and completes the WPA2 or WPA3 handshake to derive encryption keys from the password. It then obtains an IP address, gateway and DNS server with DHCP, unless it reuses a previous lease. To reach a server it resolves the name with DNS, opens a TCP connection and usually a TLS session, and only then sends the message. Each step takes time at high current, which is why caching the channel, the IP lease and the TLS session saves a lot of energy.