main.ino
Arduino (C++) · 274 lines
/*
Captive Portal: AHT20 + BMP280 (I2C) for ESP8266 / ESP32
- Device creates an OPEN Wi-Fi AP
- Captive portal opens after connecting (most OS)
- Web page shows live readings (auto-refresh via fetch)
- JSON endpoint available at /api
Wiring (I2C):
ESP 3V3 -> VDD/VCC (AHT20 + BMP280)
ESP GND -> GND
ESP SDA -> SDA (both sensors)
ESP SCL -> SCL (both sensors)
*/
#include <Wire.h>
#include <Adafruit_AHTX0.h>
#include <Adafruit_BMP280.h>
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
#elif defined(ESP32)
#include <WiFi.h>
#include <DNSServer.h>
#include <WebServer.h>
WebServer server(80);
#else
#error "This sketch supports ESP8266 or ESP32 only."
#endif
// ---------- AP / Captive Portal settings ----------
const char* AP_SSID = "ESP-Sensors";
const char* AP_PASS = ""; // empty = open Wi-Fi
const byte DNS_PORT = 53;
DNSServer dnsServer;
// Captive portal IP
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
// ---------- Sensors ----------
Adafruit_AHTX0 aht;
Adafruit_BMP280 bmp; // I2C
// Sea-level pressure used for altitude estimation (adjust for your location)
const float SEA_LEVEL_HPA = 1013.25;
// Optional explicit I2C pins:
// ESP8266 typical: SDA=D2(GPIO4), SCL=D1(GPIO5)
// ESP32 typical: SDA=21, SCL=22
#if defined(ESP32)
const int I2C_SDA = 21;
const int I2C_SCL = 22;
#elif defined(ESP8266)
const int I2C_SDA = D2;
const int I2C_SCL = D1;
#endif
// Cached readings
struct Readings {
float ahtTempC = NAN;
float ahtHumPct = NAN;
float bmpTempC = NAN;
float bmpPressHpa = NAN;
float bmpAltM = NAN;
unsigned long lastMs = 0;
} R;
void updateReadings() {
// Update at most ~2 Hz
const unsigned long now = millis();
if (now - R.lastMs < 500) return;
R.lastMs = now;
// AHT20
sensors_event_t hum, temp;
aht.getEvent(&hum, &temp);
R.ahtTempC = temp.temperature;
R.ahtHumPct = hum.relative_humidity;
// BMP280
R.bmpTempC = bmp.readTemperature(); // °C
float pPa = bmp.readPressure(); // Pa
R.bmpPressHpa = pPa / 100.0f; // hPa
R.bmpAltM = bmp.readAltitude(SEA_LEVEL_HPA); // m
}
String jsonReadings() {
updateReadings();
String s = "{";
s += "\"aht20_temp_c\":" + String(R.ahtTempC, 2) + ",";
s += "\"aht20_hum_pct\":" + String(R.ahtHumPct, 2) + ",";
s += "\"bmp280_temp_c\":" + String(R.bmpTempC, 2) + ",";
s += "\"bmp280_press_hpa\":" + String(R.bmpPressHpa, 2) + ",";
s += "\"bmp280_alt_m\":" + String(R.bmpAltM, 1);
s += "}";
return s;
}
const char INDEX_HTML[] PROGMEM = R"HTML(
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>ESP Sensors Portal</title>
<style>
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; margin: 18px; }
.card { max-width: 520px; padding: 16px; border: 1px solid #ddd; border-radius: 14px; }
h1 { font-size: 20px; margin: 0 0 12px 0; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.box { padding: 12px; border: 1px solid #eee; border-radius: 12px; }
.label { font-size: 12px; opacity: .7; margin-bottom: 6px; }
.val { font-size: 22px; font-weight: 650; }
.foot { margin-top: 10px; font-size: 12px; opacity: .7; }
button { padding: 10px 12px; border-radius: 12px; border: 1px solid #ddd; background: #fff; }
.row { display:flex; gap:10px; align-items:center; margin-top: 12px; }
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
</style>
</head>
<body>
<div class="card">
<h1>🌡️ AHT20 + BMP280 (I2C)</h1>
<div class="grid">
<div class="box">
<div class="label">AHT20 Temperature</div>
<div class="val"><span id="ahtT">--</span> °C</div>
</div>
<div class="box">
<div class="label">AHT20 Humidity</div>
<div class="val"><span id="ahtH">--</span> %</div>
</div>
<div class="box">
<div class="label">BMP280 Pressure</div>
<div class="val"><span id="bmpP">--</span> hPa</div>
</div>
<div class="box">
<div class="label">BMP280 Temperature</div>
<div class="val"><span id="bmpT">--</span> °C</div>
</div>
<div class="box" style="grid-column: 1 / -1;">
<div class="label">Altitude (estimated)</div>
<div class="val"><span id="bmpA">--</span> m</div>
</div>
</div>
<div class="row">
<button onclick="refreshNow()">Refresh</button>
<div style="font-size:12px;opacity:.75;">API: <code>/api</code> (JSON)</div>
</div>
<div class="foot">Auto-updates every 2 seconds.</div>
</div>
<script>
async function refreshNow() {
try {
const r = await fetch('/api', { cache: 'no-store' });
const j = await r.json();
document.getElementById('ahtT').textContent = Number(j.aht20_temp_c).toFixed(2);
document.getElementById('ahtH').textContent = Number(j.aht20_hum_pct).toFixed(2);
document.getElementById('bmpP').textContent = Number(j.bmp280_press_hpa).toFixed(2);
document.getElementById('bmpT').textContent = Number(j.bmp280_temp_c).toFixed(2);
document.getElementById('bmpA').textContent = Number(j.bmp280_alt_m).toFixed(1);
} catch (e) { /* ignore */ }
}
refreshNow();
setInterval(refreshNow, 2000);
</script>
</body>
</html>
)HTML";
bool initAHT20() {
if (!aht.begin()) return false;
return true;
}
bool initBMP280() {
// Common BMP280 I2C addresses: 0x76 or 0x77
if (bmp.begin(0x76)) return true;
if (bmp.begin(0x77)) return true;
return false;
}
void handleRoot() {
server.sendHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
server.sendHeader("Pragma", "no-cache");
server.send(200, "text/html; charset=utf-8", FPSTR(INDEX_HTML));
}
void handleAPI() {
server.sendHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
server.sendHeader("Pragma", "no-cache");
server.send(200, "application/json; charset=utf-8", jsonReadings());
}
void handleCaptivePortal() {
// Common OS captive portal checks:
// Android: /generate_204
// Apple: /hotspot-detect.html
// Windows: /fwlink, /ncsi.txt, /connecttest.txt
// Serve the same portal page for all of them.
handleRoot();
}
void setupCaptivePortal() {
#if defined(ESP8266)
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
WiFi.softAP(AP_SSID); // open
#elif defined(ESP32)
WiFi.mode(WIFI_MODE_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
WiFi.softAP(AP_SSID, AP_PASS); // empty password => open (core dependent, usually works)
#endif
delay(100);
// DNS wildcard: redirect all domains to our AP IP
dnsServer.start(DNS_PORT, "*", apIP);
// Main routes
server.on("/", HTTP_GET, handleRoot);
server.on("/api", HTTP_GET, handleAPI);
// Captive portal detection endpoints
server.on("/generate_204", HTTP_GET, handleCaptivePortal);
server.on("/hotspot-detect.html", HTTP_GET, handleCaptivePortal);
server.on("/fwlink", HTTP_GET, handleCaptivePortal);
server.on("/connecttest.txt", HTTP_GET, handleCaptivePortal);
server.on("/ncsi.txt", HTTP_GET, handleCaptivePortal);
// Catch-all: serve portal for any unknown path
server.onNotFound([]() { handleRoot(); });
server.begin();
}
void setup() {
Serial.begin(115200);
delay(200);
#if defined(ESP32) || defined(ESP8266)
Wire.begin(I2C_SDA, I2C_SCL);
#else
Wire.begin();
#endif
const bool okAHT = initAHT20();
const bool okBMP = initBMP280();
Serial.println();
Serial.println("--- ESP Captive Portal Sensors ---");
Serial.print("AHT20: "); Serial.println(okAHT ? "OK" : "NOT FOUND");
Serial.print("BMP280: "); Serial.println(okBMP ? "OK" : "NOT FOUND");
setupCaptivePortal();
Serial.print("AP SSID: ");
Serial.println(AP_SSID);
Serial.print("Portal IP: ");
Serial.println(apIP);
Serial.println("Connect to Wi-Fi and open the captive portal (or browse to http://192.168.4.1/).");
}
void loop() {
dnsServer.processNextRequest();
server.handleClient();
}