main.ino
Arduino (C++) · 271 lines
/* =========================================================================
HLK-LD2410C (24 GHz radar) — TESTER with captive portal (ESP32)
-------------------------------------------------------------------------
The program creates an open WiFi Access Point + captive portal.
After a phone/laptop connects, a page opens automatically that shows
live data from the LD2410C radar module:
- whether the module is connected and "talking" over UART (=> healthy),
- whether human presence / motion is detected,
- distance and "energy" of the moving and stationary (micro-motion) target,
- overall detection distance.
This makes it immediately clear that the sensor does its job.
=========================================================================
WIRING (LD2410C <-> ESP32 / ESP32-DevKitC):
LD2410C VCC -> 5V / VIN (module powered with 5–12 V)
LD2410C GND -> GND (COMMON ground with the ESP!)
LD2410C TX -> ESP32 GPIO16 (RX2) <-- hardware UART2
LD2410C RX -> ESP32 GPIO17 (TX2) <-- hardware UART2
LD2410C OUT -> (optional) any GPIO — hardware presence signal
NOTE: By default the LD2410C transmits over UART at 256000 baud (8N1).
The ESP32 has a separate hardware UART2, so the radar does NOT conflict
with USB (UART0) — the USB cable can stay plugged in for power.
The module output logic level is 3.3 V — compatible with the ESP32 (no shifter).
LIBRARY: "ld2410" (author: ncmreynolds)
Arduino IDE -> Tools -> Manage Libraries -> search "ld2410"
========================================================================= */
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <ld2410.h>
// =======================
// RADAR (LD2410C) CONFIG
// =======================
#define RADAR_SERIAL Serial2 // hardware UART2
#define RADAR_BAUD 256000 // LD2410C default baud rate
#define RADAR_RX_PIN 16 // ESP32 RX2 <- LD2410C TX
#define RADAR_TX_PIN 17 // ESP32 TX2 -> LD2410C RX
ld2410 radar;
// =======================
// LED CONFIGURATION
// =======================
// The ESP32-DevKitC on-board LED is on GPIO2 and uses NORMAL logic
// (HIGH = ON). It lights up when the radar detects presence — an extra signal.
#define LED_PIN 2 // GPIO2
// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* ap_ssid = "ESP32-LD2410C"; // open AP (no password)
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
// =======================
// DNS / CAPTIVE PORTAL
// =======================
const byte DNS_PORT = 53;
DNSServer dnsServer;
WebServer server(80);
// =======================
// LED CONTROL
// =======================
void setLed(bool on) {
// ESP32-DevKitC logic: HIGH = ON, LOW = OFF
digitalWrite(LED_PIN, on ? HIGH : LOW);
}
// =======================
// HTML PAGE (dashboard)
// =======================
// The page fetches data from /data (JSON) every 500 ms and refreshes the view
// without reloading. The "dot" color shows whether the module is healthy.
String htmlPage() {
String html =
"<!DOCTYPE html><html><head>"
"<meta charset='UTF-8'>"
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
"<title>LD2410C Tester</title>"
"<style>"
"body{font-family:sans-serif;margin:0;padding:20px;background:#0f172a;color:#e2e8f0;}"
"h2{margin-top:0;}"
".dot{display:inline-block;width:14px;height:14px;border-radius:50%;margin-right:8px;vertical-align:middle;background:#64748b;}"
".ok{background:#22c55e;box-shadow:0 0 10px #22c55e;}"
".bad{background:#ef4444;box-shadow:0 0 10px #ef4444;}"
".card{background:#1e293b;border-radius:12px;padding:16px 18px;margin:12px 0;}"
".big{font-size:28px;font-weight:700;}"
".row{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #334155;}"
".row:last-child{border-bottom:none;}"
".lbl{color:#94a3b8;}"
".val{font-weight:600;}"
".present{color:#22c55e;}"
".absent{color:#94a3b8;}"
".bar{height:8px;background:#334155;border-radius:4px;overflow:hidden;margin-top:4px;}"
".bar>span{display:block;height:100%;background:#38bdf8;width:0%;transition:width .3s;}"
".foot{color:#64748b;font-size:13px;margin-top:16px;line-height:1.5;}"
"</style>"
"</head><body>";
html += "<h2>📡 HLK-LD2410C radar tester</h2>";
html += "<div class='card'>"
"<div><span id='dot' class='dot'></span>"
"<span id='conn' class='big'>…</span></div>"
"</div>";
html += "<div class='card'>"
"<div class='big' id='presence'>…</div>"
"<div class='lbl' id='presenceSub'>detection status</div>"
"</div>";
html += "<div class='card'>"
"<div class='row'><span class='lbl'>Motion — distance</span>"
"<span class='val' id='mDist'>—</span></div>"
"<div class='bar'><span id='mBar'></span></div>"
"<div class='row'><span class='lbl'>Motion — energy</span>"
"<span class='val' id='mEner'>—</span></div>"
"</div>";
html += "<div class='card'>"
"<div class='row'><span class='lbl'>Micro-motion — distance</span>"
"<span class='val' id='sDist'>—</span></div>"
"<div class='bar'><span id='sBar'></span></div>"
"<div class='row'><span class='lbl'>Micro-motion — energy</span>"
"<span class='val' id='sEner'>—</span></div>"
"</div>";
html += "<div class='card'>"
"<div class='row'><span class='lbl'>Detection distance</span>"
"<span class='val' id='dDist'>—</span></div>"
"</div>";
html += "<div class='foot'>"
"Network <b>ESP32-LD2410C</b> (open). This page should open "
"automatically as a captive portal.<br>"
"Green dot = the module is streaming UART data (healthy)."
"</div>";
// Data-updating script
html += "<script>"
"function fmt(v){return v+' cm';}"
"async function upd(){"
"try{"
"let r=await fetch('/data');let d=await r.json();"
"let dot=document.getElementById('dot');"
"let conn=document.getElementById('conn');"
"if(d.connected){dot.className='dot ok';conn.textContent='Module HEALTHY';}"
"else{dot.className='dot bad';conn.textContent='No data from module';}"
"let p=document.getElementById('presence');"
"let ps=document.getElementById('presenceSub');"
"if(d.presence){p.textContent='\\u2713 Presence detected';p.className='big present';"
"ps.textContent=(d.moving?'motion ':'')+(d.stationary?'micro-motion':'');}"
"else{p.textContent='\\u2014 No presence';p.className='big absent';ps.textContent='empty';}"
"document.getElementById('mDist').textContent=fmt(d.movingDistance);"
"document.getElementById('mEner').textContent=d.movingEnergy;"
"document.getElementById('mBar').style.width=Math.min(d.movingEnergy,100)+'%';"
"document.getElementById('sDist').textContent=fmt(d.stationaryDistance);"
"document.getElementById('sEner').textContent=d.stationaryEnergy;"
"document.getElementById('sBar').style.width=Math.min(d.stationaryEnergy,100)+'%';"
"document.getElementById('dDist').textContent=fmt(d.detectionDistance);"
"}catch(e){}"
"}"
"setInterval(upd,500);upd();"
"</script>";
html += "</body></html>";
return html;
}
// =======================
// JSON DATA ENDPOINT
// =======================
String dataJson() {
bool connected = radar.isConnected();
bool moving = radar.movingTargetDetected();
bool stationary = radar.stationaryTargetDetected();
bool presence = radar.presenceDetected();
String j = "{";
j += "\"connected\":" + String(connected ? "true" : "false") + ",";
j += "\"presence\":" + String(presence ? "true" : "false") + ",";
j += "\"moving\":" + String(moving ? "true" : "false") + ",";
j += "\"stationary\":" + String(stationary ? "true" : "false") + ",";
j += "\"movingDistance\":" + String(radar.movingTargetDistance()) + ",";
j += "\"movingEnergy\":" + String(radar.movingTargetEnergy()) + ",";
j += "\"stationaryDistance\":" + String(radar.stationaryTargetDistance()) + ",";
j += "\"stationaryEnergy\":" + String(radar.stationaryTargetEnergy()) + ",";
j += "\"detectionDistance\":" + String(radar.detectionDistance());
j += "}";
return j;
}
// =======================
// CAPTIVE PORTAL REDIRECT
// =======================
void redirectToRoot() {
String url = "http://" + apIP.toString() + "/";
server.sendHeader("Location", url, true);
server.send(302, "text/plain", "");
}
// =======================
// HTTP HANDLERS
// =======================
void handleRoot() {
server.send(200, "text/html", htmlPage());
}
void handleData() {
server.send(200, "application/json", dataJson());
}
void handleNotFound() {
// Redirect all unknown paths -> main page (captive portal)
redirectToRoot();
}
// Captive portal detection URLs
void handleGenerate204() { handleRoot(); } // Android
void handleHotspotDetect(){ handleRoot(); } // iOS/macOS
void handleNCsi() { handleRoot(); } // Windows
// =======================
// SETUP
// =======================
void setup() {
// Status LED
pinMode(LED_PIN, OUTPUT);
setLed(false);
// Start UART2 for the radar (custom RX/TX pins — no conflict with USB)
RADAR_SERIAL.begin(RADAR_BAUD, SERIAL_8N1, RADAR_RX_PIN, RADAR_TX_PIN);
radar.begin(RADAR_SERIAL);
// Start WiFi in Access Point mode
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
WiFi.softAP(ap_ssid);
// Start DNS server (redirect all domains to the AP IP)
dnsServer.start(DNS_PORT, "*", apIP);
// Web server routes
server.on("/", handleRoot);
server.on("/data", handleData);
// Captive portal routes
server.on("/generate_204", handleGenerate204);
server.on("/hotspot-detect.html", handleHotspotDetect);
server.on("/ncsi.txt", handleNCsi);
server.onNotFound(handleNotFound);
server.begin();
}
// =======================
// LOOP
// =======================
void loop() {
radar.read(); // continuously parse frames from the LD2410C
setLed(radar.presenceDetected()); // LED = presence
dnsServer.processNextRequest();
server.handleClient();
}