Wireless, Networking and Updates
Wi-Fi, Bluetooth LE and MQTT for devices, security basics, bootloaders and safe over-the-air updates.
Connectivity options
| Link | Range | Data rate | Power | Best for |
|---|---|---|---|---|
| Wi-Fi | 20 to 50 m indoors | Mbit/s | High (100 to 240 mA transmit) | Existing networks, large payloads, OTA updates, cloud connection |
| Bluetooth LE | 10 to 50 m (up to 200+ with coded PHY) | Up to about 1 Mbit/s | Very low | Phone apps, wearables, coin-cell sensors, provisioning |
| LoRa / LoRaWAN | Kilometers | 0.3 to 50 kbit/s | Low (short bursts) | Remote, battery sensors; few small messages |
| Zigbee, Thread, Matter | 10 to 30 m, meshing | 250 kbit/s | Low | Home automation; mesh networks |
| Cellular (LTE-M, NB-IoT) | Wide area | kbit/s to Mbit/s | Medium to high | Mobile or remote devices with no local network |
| Ethernet | 100 m of cable | 10 to 100 Mbit/s | Medium (with PHY) | Fixed devices, robust links (see Industrial Communication) |
| Wired serial (RS-485, CAN) | Hundreds of meters | kbit/s to Mbit/s | Low | Machines and factories (see UART, I²C, SPI and CAN in Firmware) |
Pick the link from the range, the data volume and the power budget (see Power and Low-Power Firmware). Where a radio is used, a certified module (with an approval from the radio regulator) avoids the cost and delay of certifying your own design.
Wi-Fi in firmware
- The chip runs a stack: an ESP32 runs the radio, TCP/IP (lwIP), TLS and your application in the same chip, with an RTOS (see Firmware Architecture, State Machines and RTOS). Memory and stack sizes matter: TLS needs tens of kilobytes of RAM.
- Event-driven code: connection, disconnection and IP-assignment arrive as events; handle each, and do not assume the connection stays up.
- Wi-Fi timing is not hard real-time. Network tasks can delay other work by milliseconds: put timing-critical control on a separate core or a separate MCU, and never block on the network in the control loop.
- 2.4 GHz only for most microcontrollers; check the router’s band, channel and security mode (WPA2/WPA3). Mixed 2.4 GHz and 5 GHz networks must expose a 2.4 GHz SSID.
- Power: connecting costs more than sending. Keep the connection short, or use power-save modes and a static IP (see Power and Low-Power Firmware).
// ESP32 (Arduino core): connect with a timeout, then publish, then sleep
#include <WiFi.h>
bool wifi_connect(uint32_t timeout_ms) {
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASSWORD); // credentials come from provisioning, not the source
uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED) {
if (millis() - t0 > timeout_ms) return false; // always give up eventually
delay(100);
}
return true;
}
Bluetooth Low Energy
BLE is designed for tiny, infrequent data from small batteries. A device advertises a short packet at a set interval; a phone or hub either reads the advertisement (a beacon) or connects, after which data is exchanged in a GATT profile: services made of characteristics (a value that can be read, written or notified). Standard profiles exist for heart rate, battery level and environmental sensing; custom services carry anything else.
Worked example: advertising and throughput
- Advertising power. Each advertisement uses about 8 mA for 3 ms. At one a second the average is 8 mA × 3 ms ÷ 1 000 ms = 24 µA, plus 2 µA of sleep = 26 µA, so a 220 mAh CR2032 (80 % usable) lasts 282 days (about 0.8 years). At 10 advertisements a second (100 ms interval, for a fast discovery) the average is 242 µA and the cell lasts 30 days: the interval is the lever.
- Throughput. A connection exchanges data once per connection interval (for example 30 ms). With one 20-byte notification per interval the rate is 20 × (1 000 ÷ 30) = 667 bytes/s; with a 244-byte payload (the data-length and MTU extensions) and four packets per interval it is 244 × 4 × (1 000 ÷ 30) = 32 533 bytes/s. Sending an 800 KB image takes 20 minutes at the first rate and 0 minutes at the second.
- Slave latency lets the device skip connection events when it has nothing to send, so a connected sensor can sleep between readings.
HTTP, MQTT and message formats
| HTTP(S) (REST) | MQTT | CoAP / UDP | |
|---|---|---|---|
| Model | Request and response | Publish and subscribe through a broker | Request and response, lightweight |
| Overhead | Hundreds of bytes of headers per request | A few bytes per message once connected | A few bytes |
| Connection | New or kept alive per request | A long-lived TCP connection (with keep-alive) | None (connectionless) |
| Receive commands | Poll the server | Subscribe: the broker pushes to the device | Observe or poll |
| Best for | Simple uploads, web APIs, firmware downloads | Telemetry and control of many devices | Constrained networks |
Worked example: bytes on the wire
- MQTT publish: the topic “sensors/node1/temp” (18 bytes) with the payload “23.4” (4 bytes) takes 1 (packet type) + 1 (length) + 2 (topic length) + 18 + 4 = 26 bytes.
- HTTP POST of the JSON {“t”:23.4,”h”:51} (17 bytes) with the usual headers and an authorization token: about 162 bytes, roughly 6 times the MQTT message, before the response.
- The payload itself: the JSON reading is 17 bytes; the same in CBOR (a compact binary JSON) about 12; as two 16-bit integers (temperature in tenths of a degree and humidity in percent) only 4 bytes. On LoRa (where messages are limited to tens of bytes) a binary format is essential; on Wi-Fi a readable JSON is usually worth its cost.
- MQTT keep-alive: a connection kept open sends a ping every keep-alive interval (for example 60 s): a sleepy device cannot afford that, so connect, publish and disconnect, or use a protocol designed for sleeping nodes.
| MQTT feature | What it does |
|---|---|
| QoS 0 / 1 / 2 | At most once (fire and forget), at least once (acknowledged, may duplicate), exactly once (four-step handshake). QoS 1 is the usual choice |
| Retained message | The broker keeps the last value of a topic and gives it to every new subscriber: ideal for status and configuration |
| Last will | A message the broker publishes if the device disappears without disconnecting: shows “offline” |
| Topic design | A tree such as site/device/sensor; keep it consistent, avoid spaces and leading slashes |
| Keep-alive | How long silence is tolerated before the broker drops the client |
Staying connected: reconnects and timeouts
Networks fail: the router restarts, the cloud has an outage, a signal fades. A device must recover by itself without flooding the server when it comes back. Use exponential back-off: after each failure double the wait up to a limit, and add a little random jitter so that a thousand devices do not all reconnect at the same second.
Worked example: back-off
Waits of 1, 2, 4, 8, 16, 32, 64, 128, 256, 300 s (doubling from 1 s, capped at 300 s) over ten attempts add up to 811 s: the first few retries are quick for a short glitch, and after a long outage the device tries only every five minutes, using little battery.
- Set a timeout on every network call; never wait forever (a watchdog is the backstop: see Firmware Architecture, State Machines and RTOS).
- Queue data while offline (in RAM or flash, with a limit) and send it when the link returns; time-stamp each reading when it is taken.
- Get the time from NTP or the network, and handle a device that has not yet synchronized.
- Fail safe: a device that loses its connection must keep doing its local job, safely.
- Log the reason for every disconnection to find a flaky router or a weak signal.
Security basics
A connected device is reachable by anyone on the network, and a compromised device can attack other devices or be used for attacks. The basics apply to a hobby project as well as a product.
- Encrypt the link with TLS (HTTPS, MQTTS). The handshake is heavy: about 5 KB of data and 2 round trips (at an 80 ms round trip that is 0.16 s) and some seconds of CPU on a small MCU; session resumption and keeping the connection open save the cost, and the radio-on time is the real cost on a battery.
- Check the server’s certificate (pin the CA or the server key): a client that accepts any certificate gives no protection.
- No default or shared passwords. Give each device its own credentials, generated or provisioned in production; never put a password or key in source code that goes into a repository.
- Authenticate commands sent to the device, and check their range: a remote command must not be able to drive an actuator past a safe limit.
- Sign the firmware and check the signature in the bootloader (see below), so that only your updates run; secure boot and flash encryption are provided on many chips.
- Hashes verify integrity: SHA-256 of “abc” is
ba7816bf8f01cfea…(the full value ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad is the standard test vector); a CRC detects accidental damage but not tampering. - Minimize what is exposed: close unused ports, disable debug interfaces in production (or lock the debug port), and keep the attack surface small.
- Plan to update: vulnerabilities will be found; a device that cannot be updated securely will stay vulnerable.
Bootloaders and over-the-air updates
A bootloader is a small program at the start of flash that runs first. It decides which application to start and can receive a new one over USB, serial, Wi-Fi or Bluetooth. An over-the-air (OTA) update downloads a new firmware image while the device is in the field, writes it to flash and restarts. A failed update must never leave the device unusable (“bricked”), so the design matters more than the download.
Worked example: how long does an update take?
- An image of 800 KB over Wi-Fi at an effective 1 Mbit/s (125 KB/s, after protocol overhead) takes 800 ÷ 125 = 6.6 s. The same image over BLE at 667 bytes/s takes 20 minutes, and over a 115 200 baud UART 71 s.
- Flash writing: with 4 KB pages and about 30 ms to erase and write a page, 200 pages take 200 × 30 ms = 6.0 s (and the CPU may stall during an erase on some chips).
- Energy and time matter on a battery: do not start an update on a low battery, and keep the radio on only for the download.
- Differential updates send only the changed bytes (typically 10 to 20 % of the image), cutting the time proportionally.
- Two application slots (A/B): write the new image to the inactive slot while the old one runs; verify; then switch.
- Verify before booting: check a CRC for integrity and a digital signature for authenticity; refuse an image that fails.
- “Try once” and confirm: the new image runs; if it does not mark itself good within a set time (after connecting, say), the bootloader reverts to the old slot at the next reset, with a watchdog as the trigger.
- Protect the bootloader itself (lock it, never update it unless you can do so safely) and keep it small.
- Roll back protection: use a version counter so that an attacker cannot install an old, vulnerable image.
- Preserve data (settings, calibration) across updates in a separate area (see Memory, Number Formats and Reliability).
- Test the failure paths: pull the power in the middle of an update, corrupt an image, and check that the device recovers.
Provisioning and device identity
- Giving the device its Wi-Fi credentials: a soft-AP (the device makes its own network and a web page), BLE provisioning from a phone app, or a QR code; never put your home Wi-Fi password in firmware that you publish.
- Unique identity: use the chip’s unique ID or MAC address, and a per-device key or certificate stored in protected memory.
- Naming and topics: include the device ID in MQTT topics and logs so that each device can be tracked and commanded.
- Factory reset: a button or procedure that clears credentials and returns the device to provisioning mode.
- Time and certificates expire: a device with a certificate valid for a year or two must be able to renew it, and needs a correct clock to validate a certificate at all.
A connected-device checklist
| Check | Why |
|---|---|
| Time-outs and retries with back-off on every network call | Networks fail; battery and servers must survive it |
| Works with the network down (local control still safe) | A connected device must still be a good device |
| TLS with certificate checking; unique credentials per device | Basic security |
| Signed, A/B firmware updates tested with power cuts | Updates are how bugs and vulnerabilities get fixed |
| Watchdog and reset-cause logging | Recovery from hangs; know what happened |
| Radio-on time measured and minimized | Battery life |
| Certified radio module and compliance (CE, FCC) for the product | Legal to sell |
| Privacy: collect and send only what is needed | Trust and the law |
Related
- Embedded Systems: the overview of this guide.
- Power and Low-Power Firmware: radios and battery life.
- Memory, Number Formats and Reliability: CRCs, and where images and settings live.
- UART, I²C, SPI and CAN in Firmware: the wired side: UART, CAN and RS-485.
- Industrial Communication: OPC UA, MQTT and Ethernet in machines; Data Logging: storing and sending readings.
FAQ
MQTT or HTTP for my sensor?
MQTT when the device sends often or must receive commands (small messages, a persistent connection). HTTP for occasional uploads, simple web APIs and downloads. For a battery node that wakes every few minutes, either can work; measure the radio-on time.
Is it safe to put my Wi-Fi password in the code?
For a private prototype that stays on your computer, it is common; never publish it, and for anything you share or ship use provisioning (a soft-AP, BLE or a QR code) so that credentials are entered at set-up and stored on the device.
What happens if the power fails during an OTA update?
With an A/B layout and a verified, confirmed switch-over, nothing: the old image is still intact and the device boots it. With a single slot and no recovery, the device can be bricked, which is why the design matters.
Do I need TLS on a local network?
It is still a good idea: other devices on the network (and the internet if it is exposed) can read or change plain traffic. On small MCUs the cost is memory and the handshake time; use a certificate, resume sessions, and pick lightweight cipher suites.
References
- OASIS, MQTT Version 3.1.1 / 5.0 specifications; IETF RFC 7252 (CoAP); RFC 8446 (TLS 1.3).
- Bluetooth SIG, Core Specification (LE advertising, connection intervals and GATT); Espressif, Nordic and STMicroelectronics wireless application notes.
- MCUboot and ESP-IDF OTA documentation (A/B slots, image signing, rollback); NIST FIPS 180-4 (SHA-256).
Last reviewed: October 2026. Data rates and update times use typical figures: measure on your own network and hardware.
