main.ino

Arduino (C++) · 245 lines

#include <Arduino.h>

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

// ===================== E18-D80NK (proximity) =====================
// NPN, open-collector output:
//   - object detected  -> OUT is pulled LOW
//   - no object        -> OUT floats HIGH (thanks to INPUT_PULLUP)
//
// IMPORTANT: use a GPIO that has an internal pull-up.
// GPIO 34..39 are INPUT-ONLY and have NO pull-up -> do NOT use them here
// (or add an external 10k pull-up to 3V3 if you must).
static const uint8_t SENSOR_PIN = 4;   // OUT (black wire) -> GPIO4

// Set to true if your board/wiring inverts the logic.
// Default E18-D80NK NPN: LOW = detected.
static const bool DETECTED_IS_LOW = true;

// ===================== Captive Portal (ESP32) =====================
static const char* AP_SSID = "esp32-e18-d80nk";
static const char* AP_PASS = ""; // keep empty for an open captive portal

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

// UI/settings
String sensorLabel = "E18-D80NK";
uint16_t refreshMs = 300;

// State
bool lastDetected = false;
int  lastRaw = HIGH;
unsigned long lastChangeMs = 0;   // when the detection state last changed
unsigned long detectCount = 0;    // number of rising "object appeared" events

// ===================== Helpers =====================
String htmlEscape(const String& s) {
  String out;
  out.reserve(s.length());
  for (size_t i = 0; i < s.length(); i++) {
    char c = s[i];
    if (c == '&') out += "&amp;";
    else if (c == '<') out += "&lt;";
    else if (c == '>') out += "&gt;";
    else if (c == '"') out += "&quot;";
    else out += c;
  }
  return out;
}

// ===================== Sensor reading =====================
void initSensor() {
  pinMode(SENSOR_PIN, INPUT_PULLUP);
  lastRaw = digitalRead(SENSOR_PIN);
  lastDetected = (DETECTED_IS_LOW ? (lastRaw == LOW) : (lastRaw == HIGH));
  lastChangeMs = millis();
}

void updateSensor() {
  int raw = digitalRead(SENSOR_PIN);
  bool detected = (DETECTED_IS_LOW ? (raw == LOW) : (raw == HIGH));

  lastRaw = raw;

  if (detected != lastDetected) {
    lastDetected = detected;
    lastChangeMs = millis();
    if (detected) detectCount++;   // count new detections (object appeared)
  }
}

// ===================== Web pages =====================
String buildIndexPage() {
  String label = htmlEscape(sensorLabel);

  String page;
  page.reserve(3000);

  page += "<!doctype html><html><head><meta charset='utf-8'>";
  page += "<meta name='viewport' content='width=device-width,initial-scale=1'>";
  page += "<title>ESP32 E18-D80NK</title>";
  page += "<style>";
  page += "body{font-family:Arial;max-width:640px;margin:24px auto;padding:0 12px;}";
  page += ".card{border:1px solid #ddd;border-radius:12px;padding:16px;margin:12px 0;}";
  page += "h2{margin:0 0 12px 0;}";
  page += "input,button{font-size:16px;padding:10px;}";
  page += "input{width:100%;box-sizing:border-box;}";
  page += "button{margin-top:10px;}";
  page += ".big{font-size:40px;font-weight:700;}";
  page += ".muted{color:#666;}";
  page += ".dot{display:inline-block;width:18px;height:18px;border-radius:50%;vertical-align:middle;margin-right:8px;background:#bbb;}";
  page += ".on{background:#2ecc71;} .off{background:#e74c3c;}";
  page += "</style></head><body>";

  page += "<h2>ESP32 + E18-D80NK (Captive Portal)</h2>";

  page += "<div class='card'>";
  page += "<div class='muted'>Sensor</div>";
  page += "<div><b>" + label + "</b></div>";
  page += "<div class='muted' style='margin-top:8px'>Status</div>";
  page += "<div class='big'><span id='dot' class='dot'></span><span id='t'>--</span></div>";
  page += "<div class='muted' id='s'></div>";
  page += "<div class='muted' id='c'></div>";
  page += "</div>";

  page += "<div class='card'>";
  page += "<div class='muted'>Settings</div>";
  page += "<form action='/set' method='POST'>";
  page += "<label>Label</label><br>";
  page += "<input name='label' maxlength='40' value='" + label + "'><br><br>";
  page += "<label>Refresh (ms)</label><br>";
  page += "<input name='refresh' type='number' min='100' max='10000' value='" + String(refreshMs) + "'><br>";
  page += "<button>Save</button>";
  page += "</form>";
  page += "</div>";

  page += "<div class='muted'>Wi-Fi SSID: <b>";
  page += AP_SSID;
  page += "</b> — Open this network to use the portal.</div>";

  // JS: fetch /api every refreshMs
  page += "<script>";
  page += "let refresh=" + String(refreshMs) + ";";
  page += "async function tick(){";
  page += "  try{";
  page += "    const r=await fetch('/api',{cache:'no-store'});";
  page += "    const j=await r.json();";
  page += "    const dot=document.getElementById('dot');";
  page += "    document.getElementById('t').textContent = j.detected ? 'OBJECT' : 'clear';";
  page += "    dot.className = 'dot ' + (j.detected ? 'on' : 'off');";
  page += "    document.getElementById('s').textContent = 'state for '+j.age_ms+' ms (raw='+j.raw+')';";
  page += "    document.getElementById('c').textContent = 'detections: '+j.count;";
  page += "  }catch(e){ document.getElementById('s').textContent='fetch error'; }";
  page += "  setTimeout(tick, refresh);";
  page += "}";
  page += "tick();";
  page += "</script>";

  page += "</body></html>";
  return page;
}

void handleRoot() {
  server.send(200, "text/html", buildIndexPage());
}

void handleSet() {
  if (server.hasArg("label")) {
    String v = server.arg("label");
    v.trim();
    if (v.length() == 0) v = "E18-D80NK";
    sensorLabel = v;
  }
  if (server.hasArg("refresh")) {
    int v = server.arg("refresh").toInt();
    if (v < 100) v = 100;
    if (v > 10000) v = 10000;
    refreshMs = (uint16_t)v;
  }

  // redirect back to /
  server.sendHeader("Location", "/", true);
  server.send(302, "text/plain", "Redirecting...");
}

void handleApi() {
  updateSensor();

  unsigned long age = millis() - lastChangeMs;

  String json;
  json.reserve(200);
  json += "{";
  json += "\"detected\":"; json += (lastDetected ? "true" : "false"); json += ",";
  json += "\"raw\":"; json += String(lastRaw); json += ",";
  json += "\"age_ms\":"; json += String(age); json += ",";
  json += "\"count\":"; json += String(detectCount); json += ",";
  json += "\"label\":\""; json += htmlEscape(sensorLabel); json += "\"";
  json += "}";

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

// Captive-portal detection endpoints (helps phones pop up the portal)
void handleGenerate204() { server.sendHeader("Location", "http://192.168.4.1/", true); server.send(302, "text/plain", ""); }
void handleHotspotDetect() { server.sendHeader("Location", "http://192.168.4.1/", true); server.send(302, "text/plain", ""); }
void handleFWLink() { server.sendHeader("Location", "http://192.168.4.1/", true); server.send(302, "text/plain", ""); }

void handleNotFound() {
  server.sendHeader("Location", "http://192.168.4.1/", true);
  server.send(302, "text/plain", "");
}

// ===================== Captive portal setup =====================
void setupCaptivePortal() {
  WiFi.mode(WIFI_AP);
  if (strlen(AP_PASS) == 0) WiFi.softAP(AP_SSID);
  else WiFi.softAP(AP_SSID, AP_PASS);

  // DNS redirect: any domain -> our AP IP
  dnsServer.start(DNS_PORT, "*", WiFi.softAPIP());

  // Web routes
  server.on("/", HTTP_GET, handleRoot);
  server.on("/set", HTTP_POST, handleSet);
  server.on("/api", HTTP_GET, handleApi);

  // Captive portal helpers
  server.on("/generate_204", HTTP_GET, handleGenerate204);
  server.on("/hotspot-detect.html", HTTP_GET, handleHotspotDetect);
  server.on("/fwlink", HTTP_GET, handleFWLink);

  server.onNotFound(handleNotFound);
  server.begin();
}

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

  initSensor();
  setupCaptivePortal();

  Serial.println("Captive portal started.");
  Serial.print("AP SSID: ");
  Serial.println(AP_SSID);
  Serial.print("AP IP: ");
  Serial.println(WiFi.softAPIP());
  Serial.print("Sensor pin: GPIO");
  Serial.println(SENSOR_PIN);
}

void loop() {
  dnsServer.processNextRequest();
  server.handleClient();

  // keep sensor state fresh (also catches short pulses between HTTP requests)
  updateSensor();

  delay(2);
}