Files
Hello/firmware/src/ld2410.cpp
T

297 lines
10 KiB
C++

#include "ld2410.h"
#include <HardwareSerial.h>
#include "app_config.h"
#include "board_pins.h"
static HardwareSerial s_uart(RADAR_UART_NUM);
static RadarReading s_last = {};
// Incremental frame assembler. The radar streams continuously and we share the
// core with the camera, so parsing has to tolerate being called late and
// finding several frames queued in the driver buffer.
static uint8_t s_buf[64];
static size_t s_len = 0;
static bool s_sync = false;
static const uint8_t kReportHead[4] = {0xF4, 0xF3, 0xF2, 0xF1};
static const uint8_t kReportTail[4] = {0xF8, 0xF7, 0xF6, 0xF5};
static const uint8_t kCmdHead[4] = {0xFD, 0xFC, 0xFB, 0xFA};
static const uint8_t kCmdTail[4] = {0x04, 0x03, 0x02, 0x01};
static inline uint16_t rd16(const uint8_t* p) {
return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
}
// Baud rates to probe, most likely first. The LD2410 leaves the factory at
// 256000; 115200 is the usual choice when someone has reconfigured it.
static const uint32_t kBaudCandidates[] = {256000, 115200, 57600, 38400, 9600};
static uint32_t s_baud = 0;
uint32_t radarBaud() { return s_baud; }
// Open at `baud` and listen for a well-formed report frame.
static bool tryBaud(uint32_t baud, uint32_t listen_ms) {
s_uart.end();
delay(20);
s_uart.setRxBufferSize(512); // must precede begin()
s_uart.begin(baud, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX);
s_len = 0;
s_sync = false;
memset(&s_last, 0, sizeof(s_last));
const uint32_t end = millis() + listen_ms;
while ((int32_t)(end - millis()) > 0) {
if (radarPoll()) return true; // decoded a real frame: right baud
delay(5);
}
return false;
}
bool radarBegin() {
pinMode(PIN_RADAR_OUT, INPUT);
// Autodetect rather than hardcode. The module reports a few times a
// second, so a wrong baud is obvious within a second — and detecting it
// means a factory reset (which returns the module to 256000) does not
// silently take the camera's trigger offline on a device you cannot
// easily reach. Pin it with `radar_baud` if you would rather it not probe.
if (g_cfg.radar_baud != 0) {
if (tryBaud(g_cfg.radar_baud, 1500)) {
s_baud = g_cfg.radar_baud;
log_i("radar: UART%d @%u baud (pinned) rx=%d tx=%d out=%d",
RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT);
return true;
}
log_w("radar: no frames at the pinned %u baud, falling back to autodetect",
(unsigned)g_cfg.radar_baud);
}
for (uint32_t cand : kBaudCandidates) {
if (tryBaud(cand, 900)) {
s_baud = cand;
log_i("radar: UART%d @%u baud (detected) rx=%d tx=%d out=%d",
RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT);
return true;
}
}
// Nothing decoded. Leave the port open at the default so radarSelfTest()
// can still dump raw bytes, and so the OUT pin path keeps working —
// RADAR_OUT_PIN_ONLY mode does not need the UART at all.
s_baud = 0;
s_uart.end();
delay(20);
s_uart.setRxBufferSize(512);
s_uart.begin(RADAR_BAUD, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX);
log_w("radar: no UART frames at any baud — check TX/RX are crossed. "
"The OUT pin still works; radar_mode=0 uses it alone.");
return false;
}
// Decode a complete report payload (header and tail already stripped).
static bool decodeReport(const uint8_t* p, size_t n) {
// Basic report: 13 payload bytes. Engineering mode reports are longer and
// start the same way, so we accept anything >= 13 and read the common head.
if (n < 13) return false;
if (p[0] != 0x02 || p[1] != 0xAA) return false;
RadarReading r = {};
r.valid = true;
r.target = p[2];
r.moving_cm = rd16(&p[3]);
r.moving_energy = p[5];
r.stationary_cm = rd16(&p[6]);
r.stationary_energy = p[8];
r.detect_cm = rd16(&p[9]);
r.at_ms = millis();
r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
s_last = r;
#ifdef PB_VERBOSE_RADAR
log_d("radar: state=%u mov=%ucm/%u stat=%ucm/%u det=%ucm out=%d",
r.target, r.moving_cm, r.moving_energy,
r.stationary_cm, r.stationary_energy, r.detect_cm, r.out_pin);
#endif
return true;
}
bool radarPoll() {
bool got = false;
while (s_uart.available()) {
uint8_t b = (uint8_t)s_uart.read();
if (!s_sync) {
// Slide a 4-byte window until it matches either header.
if (s_len < 4) {
s_buf[s_len++] = b;
} else {
memmove(s_buf, s_buf + 1, 3);
s_buf[3] = b;
}
if (s_len == 4 &&
(memcmp(s_buf, kReportHead, 4) == 0 || memcmp(s_buf, kCmdHead, 4) == 0)) {
s_sync = true;
}
continue;
}
if (s_len >= sizeof(s_buf)) { // runaway frame: resynchronise
s_len = 0;
s_sync = false;
continue;
}
s_buf[s_len++] = b;
// Need header(4) + length(2) before we know how much to expect.
if (s_len < 6) continue;
const uint16_t payload_len = rd16(&s_buf[4]);
const size_t total = 4 + 2 + payload_len + 4;
if (payload_len > sizeof(s_buf) - 10) { // implausible length
s_len = 0;
s_sync = false;
continue;
}
if (s_len < total) continue;
const uint8_t* tail = &s_buf[6 + payload_len];
const bool is_rpt = memcmp(s_buf, kReportHead, 4) == 0;
const uint8_t* expect = is_rpt ? kReportTail : kCmdTail;
if (memcmp(tail, expect, 4) == 0 && is_rpt) {
got |= decodeReport(&s_buf[6], payload_len);
}
// Command ACKs are consumed silently; the write helpers below poll for
// them separately rather than routing them through this path.
s_len = 0;
s_sync = false;
}
// Keep the pin fresh even when the UART is silent (or absent).
s_last.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
return got;
}
RadarReading radarLast() {
RadarReading r = s_last;
r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
return r;
}
bool radarIsTrigger(const RadarReading& r) {
switch (g_cfg.radar_mode) {
case RADAR_OUT_PIN_ONLY:
return r.out_pin;
case RADAR_UART_ONLY:
break; // fall through to the windowed check
case RADAR_BOTH:
default:
// The pin arms; the report has to agree. If the UART has gone
// quiet (bad wiring, wrong baud) we would otherwise never trigger,
// so a stale report degrades to pin-only rather than to silence.
if (!r.out_pin) return false;
if (!r.valid || (millis() - r.at_ms) > 3000) return true;
break;
}
if (!r.valid) return false;
if (r.target == TARGET_NONE) return false;
const bool moving = (r.target == TARGET_MOVING || r.target == TARGET_BOTH);
const bool stationary = (r.target == TARGET_STATIONARY || r.target == TARGET_BOTH);
if (moving &&
r.moving_energy >= g_cfg.min_energy &&
r.moving_cm >= g_cfg.min_distance_cm &&
r.moving_cm <= g_cfg.max_distance_cm) {
return true;
}
if (stationary && g_cfg.accept_stationary &&
r.stationary_energy >= g_cfg.min_energy &&
r.stationary_cm >= g_cfg.min_distance_cm &&
r.stationary_cm <= g_cfg.max_distance_cm) {
return true;
}
return false;
}
void radarSelfTest(uint32_t duration_ms) {
log_i("radar self-test: dumping raw UART for %u ms", duration_ms);
const uint32_t end = millis() + duration_ms;
size_t bytes = 0;
uint32_t frames = 0;
while ((int32_t)(end - millis()) > 0) {
while (s_uart.available()) { s_uart.read(); bytes++; }
if (radarPoll()) frames++;
delay(5);
}
log_i("radar self-test: %u bytes, %u decoded frames, OUT=%d",
(unsigned)bytes, (unsigned)frames, digitalRead(PIN_RADAR_OUT));
if (bytes == 0) {
log_w(" no UART data. Check TX/RX are crossed and the baud rate "
"(factory 256000, some units ship at 115200).");
}
}
// --- command path -----------------------------------------------------------
// Minimal: enough to raise sensitivity if the default rejects small targets.
static bool sendCommand(const uint8_t* payload, uint16_t len, uint32_t timeout_ms = 300) {
uint8_t frame[32];
if (len + 10 > sizeof(frame)) return false;
memcpy(frame, kCmdHead, 4);
frame[4] = len & 0xFF;
frame[5] = (len >> 8) & 0xFF;
memcpy(frame + 6, payload, len);
memcpy(frame + 6 + len, kCmdTail, 4);
while (s_uart.available()) s_uart.read(); // drop queued reports
s_uart.write(frame, len + 10);
s_uart.flush();
// The ACK mirrors the command word with bit 8 set. We only check that
// *something* well-formed came back; the module is not chatty enough for
// a mismatched ACK to be ambiguous in practice.
const uint32_t end = millis() + timeout_ms;
while ((int32_t)(end - millis()) > 0) {
if (s_uart.available() >= 10) return true;
delay(5);
}
log_w("radar: no ACK for command 0x%02X%02X", payload[1], payload[0]);
return false;
}
bool radarEnterConfig() {
const uint8_t p[] = {0xFF, 0x00, 0x01, 0x00};
return sendCommand(p, sizeof(p));
}
bool radarExitConfig() {
const uint8_t p[] = {0xFE, 0x00};
bool ok = sendCommand(p, sizeof(p));
s_len = 0; s_sync = false; // report stream resumes; drop partial state
return ok;
}
bool radarSetGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary) {
if (gate > 8) return false;
// Command 0x0064: three (param-id, uint32 value) pairs.
const uint8_t p[] = {
0x64, 0x00,
0x00, 0x00, gate, 0x00, 0x00, 0x00,
0x01, 0x00, moving, 0x00, 0x00, 0x00,
0x02, 0x00, stationary, 0x00, 0x00, 0x00,
};
return sendCommand(p, sizeof(p));
}