Wireless Communication
WiFi with ESP32, Bluetooth LE, and LoRa for long-range IoT
Skills taught: embedded.wireless
The ESP32: WiFi + Bluetooth on One Chip
The ESP32 from Espressif is the workhorse of modern IoT. It packs a 240 MHz dual-core CPU, 520 KB SRAM, WiFi 802.11 b/g/n, Bluetooth 5.0 LE, and 34 GPIO pins — all for $3–5. Install the ESP32 Arduino core via Board Manager: search for esp32 by Espressif.
#include <WiFi.h>
// Store credentials outside source code in production
const char* SSID = "YourNetwork";
const char* PASS = "YourPassword";
void setup() {
Serial.begin(115200);
Serial.print(F("Connecting to WiFi"));
WiFi.begin(SSID, PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print('.');
}
Serial.println();
Serial.print(F("Connected! IP: "));
Serial.println(WiFi.localIP());
Serial.print(F("RSSI: "));
Serial.print(WiFi.RSSI());
Serial.println(F(" dBm"));
}
HTTP Requests: Sending Sensor Data to an API
Once connected to WiFi, the ESP32 can make HTTP GET/POST requests using the HTTPClient library. Use this to push sensor data to REST APIs, home automation platforms, or cloud services.
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Library Manager: ArduinoJson by Benoit Blanchon
const char* SSID = "YourNetwork";
const char* PASS = "YourPassword";
const char* API_URL = "https://api.example.com/sensors";
const char* API_KEY = "your-api-key";
void sendReading(float temp, float humidity) {
if (WiFi.status() != WL_CONNECTED) return;
HTTPClient http;
http.begin(API_URL);
http.addHeader("Content-Type", "application/json");
http.addHeader("X-API-Key", API_KEY);
// Build JSON body
StaticJsonDocument<200> doc;
doc["device_id"] = "sensor-01";
doc["temperature"] = temp;
doc["humidity"] = humidity;
doc["timestamp"] = millis() / 1000;
String body;
serializeJson(doc, body);
int code = http.POST(body);
Serial.print(F("HTTP POST: ")); Serial.println(code);
http.end();
}
void setup() {
Serial.begin(115200);
WiFi.begin(SSID, PASS);
while (WiFi.status() != WL_CONNECTED) delay(500);
Serial.println(F("WiFi ready"));
}
void loop() {
sendReading(23.4, 55.1);
delay(30000); // send every 30 seconds
}
ESP32 as a Web Server
The ESP32 can serve a web page over your local network — no cloud needed. Connect to the same WiFi and open the ESP32's IP address in a browser to control GPIO pins or view sensor readings in real time.
#include <WiFi.h>
#include <WebServer.h>
const char* SSID = "YourNetwork";
const char* PASS = "YourPassword";
WebServer server(80);
const int LED_PIN = 2;
void handleRoot() {
String html = "<html><body>";
html += "<h1>ESP32 Web Control</h1>";
html += "<p>LED: <a href='/on'>ON</a> | <a href='/off'>OFF</a></p>";
html += "<p>Uptime: " + String(millis()/1000) + " s</p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
WiFi.begin(SSID, PASS);
while (WiFi.status() != WL_CONNECTED) delay(500);
Serial.print(F("Web server at http://"));
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/on", []() { digitalWrite(LED_PIN, HIGH); server.sendHeader("Location", "/"); server.send(302); });
server.on("/off", []() { digitalWrite(LED_PIN, LOW); server.sendHeader("Location", "/"); server.send(302); });
server.begin();
}
void loop() {
server.handleClient();
}
Wireless Technology Comparison
WiFi vs LoRa for IoT
- WiFi (ESP32): 802.11 b/g/n, 2.4/5 GHz
- LoRa (SX1276): Sub-GHz spread-spectrum radio
Tip: Store WiFi credentials in ESP32's NVS (non-volatile storage) using the Preferences library rather than hardcoding them. For production devices, implement a WiFiManager access-point setup mode so users can configure their own network without reflashing firmware.
Warning: ESP32 WiFi consumes 160–300 mA during transmission bursts. A standard 9V alkaline battery (~500 mAh) will last only ~3 hours in continuous WiFi mode. For battery-powered sensors, use deep sleep between readings — a 10-second wake cycle with 10-minute sleep reduces average current to ~15 µA, lasting months on a LiPo.
Frequently Asked Questions
What is the range of Bluetooth LE on ESP32?
Typically 10–100 metres line-of-sight depending on antenna and obstacles. BLE 5.0 (supported by ESP32) extends range to ~200 m in open areas using long-range coded PHY. Good for local wearables, beacons, and mobile app control.
How do I store WiFi credentials securely on ESP32?
Use the Preferences library which writes to ESP32's NVS (Non-Volatile Storage) in an encrypted flash partition. For production, implement WiFiManager: ESP32 starts as an AP with a captive portal on first boot so the user enters their own credentials.
My ESP32 keeps disconnecting from WiFi. How do I add auto-reconnect?
Add `WiFi.setAutoReconnect(true); WiFi.persistent(true);` in setup(). Also check WiFi.status() periodically in loop() and call WiFi.reconnect() if it returns WL_DISCONNECTED. Use a watchdog timer (esp_task_wdt) for recovery if reconnect fails.