main.ino

Arduino (C++) · 170 lines

#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>

#include <DHT.h>
#include <Adafruit_Sensor.h>

// -------------------- Wi-Fi Captive Portal settings --------------------
static const char* AP_SSID = "DHT22-Portal";
static const char* AP_PASS = ""; // empty = open network (no login)

static const byte DNS_PORT = 53;
DNSServer dnsServer;
WebServer webServer(80);

IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);

// -------------------- DHT22 settings --------------------
#define DHT_PIN   4
#define DHT_TYPE  DHT22

DHT dht(DHT_PIN, DHT_TYPE);

float lastTempC = NAN;
float lastHum = NAN;
unsigned long lastReadMs = 0;

static const unsigned long READ_INTERVAL_MS = 2000; // DHT22 recommended >= 2s

// -------------------- Helpers --------------------
String formatFloat(float v, uint8_t decimals = 1) {
  if (isnan(v)) return "N/A";
  // Fix: avoid ambiguous overload on ESP32 core 3.3.6
  return String((double)v, (unsigned int)decimals);
}

void readDHTIfDue() {
  unsigned long now = millis();
  if (now - lastReadMs < READ_INTERVAL_MS) return;
  lastReadMs = now;

  float h = dht.readHumidity();
  float t = dht.readTemperature(); // Celsius

  if (!isnan(h)) lastHum = h;
  if (!isnan(t)) lastTempC = t;

  Serial.print("DHT22 -> T: ");
  Serial.print(formatFloat(lastTempC));
  Serial.print(" C, H: ");
  Serial.print(formatFloat(lastHum));
  Serial.println(" %");
}

// -------------------- Web handlers --------------------
void handleRoot() {
  String page =
    "<!doctype html><html><head>"
    "<meta charset='utf-8'/>"
    "<meta name='viewport' content='width=device-width,initial-scale=1'/>"
    "<title>DHT22 Captive Portal</title>"
    "<style>"
    "body{font-family:system-ui,Arial,sans-serif;margin:16px;}"
    ".card{max-width:720px;padding:16px;border:1px solid #ddd;border-radius:12px;}"
    ".row{display:flex;gap:12px;flex-wrap:wrap;}"
    ".pill{display:inline-block;padding:6px 10px;border-radius:999px;border:1px solid #ccc;}"
    ".big{font-size:28px;font-weight:700;margin:8px 0;}"
    "</style>"
    "</head><body>"
    "<div class='card'>"
    "<h2>ESP32 DHT22 Captive Portal</h2>"
    "<div class='row'>"
    "<div class='pill'>SSID: <b>" + String(AP_SSID) + "</b></div>"
    "<div class='pill'>IP: <b>" + apIP.toString() + "</b></div>"
    "</div>"

    "<p>Live readings refresh automatically.</p>"

    "<div class='big'>"
    "Temp: <span id='t'>--</span> &deg;C<br/>"
    "Humidity: <span id='h'>--</span> %"
    "</div>"

    "<div id='meta' class='pill'>Loading...</div>"

    "<p style='margin-top:12px;'>If the captive portal does not open automatically, go to "
    "<b>http://" + apIP.toString() + "/</b></p>"

    "</div>"

    "<script>"
    "async function refresh(){"
    "  try{"
    "    const r = await fetch('/data');"
    "    const j = await r.json();"
    "    document.getElementById('t').textContent = (j.temp_c === null) ? 'N/A' : j.temp_c.toFixed(1);"
    "    document.getElementById('h').textContent = (j.hum === null) ? 'N/A' : j.hum.toFixed(1);"
    "    document.getElementById('meta').textContent = 'Age: ' + j.age_ms + ' ms';"
    "  }catch(e){"
    "    document.getElementById('meta').textContent = 'Error: ' + e;"
    "  }"
    "}"
    "setInterval(refresh, 1000);"
    "refresh();"
    "</script>"

    "</body></html>";

  webServer.send(200, "text/html", page);
}

void handleData() {
  unsigned long age = (lastReadMs == 0) ? 0 : (millis() - lastReadMs);

  String json = "{";
  if (isnan(lastTempC)) json += "\"temp_c\":null,";
  else json += "\"temp_c\":" + String((double)lastTempC, 1) + ",";

  if (isnan(lastHum)) json += "\"hum\":null,";
  else json += "\"hum\":" + String((double)lastHum, 1) + ",";

  json += "\"age_ms\":" + String(age);
  json += "}";

  webServer.send(200, "application/json", json);
}

void handleNotFound() {
  // Captive portal behavior: redirect any unknown path to "/"
  webServer.sendHeader("Location", String("http://") + apIP.toString() + "/", true);
  webServer.send(302, "text/plain", "");
}

void setupCaptivePortal() {
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, netMsk);

  if (strlen(AP_PASS) == 0) WiFi.softAP(AP_SSID);
  else WiFi.softAP(AP_SSID, AP_PASS);

  // DNS wildcard: resolve all hostnames to our AP IP
  dnsServer.start(DNS_PORT, "*", apIP);

  webServer.on("/", handleRoot);
  webServer.on("/data", handleData);
  webServer.onNotFound(handleNotFound);

  webServer.begin();
}

void setup() {
  Serial.begin(115200);
  delay(200);

  dht.begin();
  setupCaptivePortal();

  Serial.println("Captive portal started.");
  Serial.print("Connect to AP: ");
  Serial.println(AP_SSID);
  Serial.print("Open: http://");
  Serial.println(apIP);
}

void loop() {
  dnsServer.processNextRequest();
  webServer.handleClient();
  readDHTIfDue();
}