# main.ino

- Project: [esp8266-keypad](https://flashesp.com/explore/qth3ARZvMzXWvKb6ikj39.md) by Mikrobot.pl
- Board: NodeMCU 1.0 (ESP-12E Module)
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/qth3ARZvMzXWvKb6ikj39/files/WxnVnOC0Je6m0a7jfwaPr

```cpp
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <Keypad.h>

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

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

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

// -------------------- Keypad settings (3 columns x 4 rows) --------------------
const byte ROWS = 4;
const byte COLS = 3;

// Standard 3x4 keypad layout
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

// NodeMCU "Dx" pin mapping to GPIO:
// D1=GPIO5, D2=GPIO4, D5=GPIO14, D6=GPIO12, D7=GPIO13, D3=GPIO0, D4=GPIO2
byte rowPins[ROWS] = { D1, D2, D5, D6 };
byte colPins[COLS] = { D7, D3, D4 };

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// Last key pressed (shared with web UI)
String lastKey = "None";
unsigned long lastKeyMs = 0;

// -------------------- Helpers --------------------
String jsonEscape(const String& s) {
  String out;
  out.reserve(s.length() + 8);
  for (size_t i = 0; i < s.length(); i++) {
    char c = s[i];
    if (c == '\\') out += "\\\\";
    else if (c == '"') out += "\\\"";
    else if (c == '\n') out += "\\n";
    else if (c == '\r') out += "\\r";
    else out += c;
  }
  return out;
}

// -------------------- 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>ESP8266 Keypad 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:44px;font-weight:800;margin:10px 0;}"
    "</style>"
    "</head><body>"
    "<div class='card'>"
    "<h2>ESP8266 3x4 Keypad 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>Press any button on the keypad. The last pressed key will appear below.</p>"
    "<div class='big' id='k'>--</div>"
    "<div class='pill' id='meta'>Loading...</div>"
    "<p style='margin-top:12px;'>If the 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('k').textContent = j.last_key;"
    "    document.getElementById('meta').textContent = 'Age: ' + j.age_ms + ' ms';"
    "  }catch(e){"
    "    document.getElementById('meta').textContent = 'Error: ' + e;"
    "  }"
    "}"
    "setInterval(refresh, 250);"
    "refresh();"
    "</script>"
    "</body></html>";

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

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

  String json = "{";
  json += "\"last_key\":\"" + jsonEscape(lastKey) + "\",";
  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();
}

// -------------------- Arduino entry points --------------------
void setup() {
  Serial.begin(115200);
  delay(200);

  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();

  // Read keypad (non-blocking)
  char k = keypad.getKey();
  if (k) {
    lastKey = String(k);
    lastKeyMs = millis();
    Serial.print("Key pressed: ");
    Serial.println(lastKey);
  }
}
```
