HLK LD2420

Thoms85
Posts: 2
Joined: Wed Jan 01, 2025 7:50 pm

HLK LD2420

Postby Thoms85 » Wed Jan 01, 2025 8:14 pm

Hi there,

i ordered some HLK LD2420 presence sensors from AliExpress (https://www.aliexpress.com/item/1005005 ... ry_from%3A), now i try to get them to work using my ESP32 DevKit (I think V2, but not 100% sure from here https://www.az-delivery.de/products/esp ... pmentboard).

Im using PlatformIO or Arduino IDE

I was going to use a 3rd party library: https://github.com/Bolukan/ld2420

but i cant get it to work.

here is my code:

Code: Untitled.cpp Select all


#include <Arduino.h>
#include <ld2410.h>

#define STATUS_LED 25
#define RX_PIN 33
#define TX_PIN 32
#define OT2_PIN 27

ld2410 sensor;
uint8_t statusPinState = HIGH;
unsigned long lastStatusLedToggle = 0;
const unsigned long toogleInterval = 3000;
unsigned long lastReadSensor = 0;
const unsigned long readSensorInterval = 1000;

void toggleStatusLED();
void readSensor();

void setup()
{
Serial.begin(115200);
Serial2.begin(256000, SERIAL_8N1, RX_PIN, TX_PIN);
delay(100); // Add delay after Serial2 initialization
pinMode(OT2_PIN, INPUT);
pinMode(STATUS_LED, OUTPUT);
digitalWrite(STATUS_LED, HIGH);
Serial.println("starting");

if (sensor.begin(Serial2))
{
// Enable debugging
sensor.debug(Serial2); // Request firmware version and current configuration
sensor.requestFirmwareVersion();
sensor.requestCurrentConfiguration();
Serial.println("LD2420 initialized successfully!");
// sensor.setsetSensitivity(5); // Setzt die Empfindlichkeit (1-9)
// sensor.setDistanceRange(0, 500); // Setzt den Distanzbereich (0-500 cm)
// sensor.setVelocityRange(0, 200); // Setzt den Geschwindigkeitsbereich (0-200 cm/s)
Serial.println("LD2420 configured successfully!");
}
else
{
Serial.println("Failed to initialize LD2420.");
}
delay(3000);
}

void loop()
{
Serial.println("loop");
unsigned long now = millis();
sensor.read();
// toggle status led
if (now - lastStatusLedToggle >= toogleInterval)
{
toggleStatusLED();
lastStatusLedToggle = now;
//Serial.println("switchLED");
}

if (now - lastReadSensor >= readSensorInterval)
{
readSensor();
lastReadSensor = now;
}
delay(500);
}

void toggleStatusLED()
{
Serial.println("toggle");
if (statusPinState == HIGH)
{
statusPinState = LOW;
digitalWrite(STATUS_LED, LOW);
}
else
{
statusPinState = HIGH;
digitalWrite(STATUS_LED, HIGH);
}
}

void readSensor()
{
// Check connection
if (sensor.isConnected())
{
Serial.println("LD2420 is connected and sending data."); // Presence detection
}
else
{
Serial.println("LD2420 is not connected.");
}
if (sensor.presenceDetected())
{
Serial.println("Presence detected!"); // Stationary target detection
if (sensor.stationaryTargetDetected())
{
Serial.print("Stationary Target Distance: ");
Serial.println(sensor.stationaryTargetDistance());
Serial.print("Stationary Target Energy: ");
Serial.println(sensor.stationaryTargetEnergy());
} // Moving target detection
if (sensor.movingTargetDetected())
{
Serial.print("Moving Target Distance: ");
Serial.println(sensor.movingTargetDistance());
Serial.print("Moving Target Energy: ");
Serial.println(sensor.movingTargetEnergy());
}
}
int ot2_state = digitalRead(OT2_PIN);
Serial.print("OT2: ");
Serial.println(ot2_state);
}
Excuse the delay() those are only for debug purposes.

but i cant get the communication to work i always get

"Failed to initialize LD2420."

I tried switching RX/TX(OT1) and even RX/OT1/OT2, BaudRates between 115200 and 256000, and exchanged the sensors (since I got 5) nothing works.
The sensor is supplied with 3.1V which should be enough since its accepting 3.0-3.6V. All pins Output 3.1V so i guess its wired correctly.

Does anyone have experience with the LD2420? And can help me out/push me in the right direction?

Thanks in advance.

MicroController
Posts: 2672
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: HLK LD2420

Postby MicroController » Thu Jan 02, 2025 12:53 pm

Does the sensor work when connected to a PC via USB<->serial adapter?
Do the ESP and the sensor have a common GND?

Code: Select all

  if (sensor.begin(Serial2))
  {
    // Enable debugging
    sensor.debug(Serial2); // Request firmware version and current configuration
will send the debugging output to the sensor, which won't work.

Thoms85
Posts: 2
Joined: Wed Jan 01, 2025 7:50 pm

Re: HLK LD2420

Postby Thoms85 » Sun Jan 05, 2025 12:24 pm

Hi,

ESP and sensor do share a common ground, the sensors ground is directly hooked up to ESPs 3.3V and GND,

I dont have a USB to Serial Adapter, so i cant check.
But i got it to work somehow using HarwareSerial.h

Code: Select all

#include <HardwareSerial.h>

#define RADAR_RX_PIN 33  // RX pin on ESP32
#define RADAR_TX_PIN 32  // TX pin on ESP32
#define OT2_PIN 27
#define BUFFER_SIZE 256  // Define a buffer size
#define LED_PIN 25

char incomingBuffer[BUFFER_SIZE];  // Buffer to store incoming data
int bufferIndex = 0;               // Index to keep track of buffer position
bool startReading = true;


void setup() {
  pinMode(OT2_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);                                          
  Serial2.begin(115200, SERIAL_8N1, RADAR_RX_PIN, RADAR_TX_PIN);  
  delay(200);                                           
  Serial.println("Starting...");
  Serial2.println("test");
}

void loop() {  // Check if data is available on Serial2
  startReading = true;
  if (Serial2.available()) {
    //Serial.println(Serial2.available());
    while (Serial2.available() && startReading) {
      char incomingByte = Serial2.read();  // Read a byte
      if (incomingByte == '\n') {          // If newline character is detected, terminate the string and process the message
        incomingBuffer[bufferIndex] = '\0';
        onReceiveFinished(String(incomingBuffer));
        bufferIndex = 0;  // Reset buffer index for the next message
        startReading = false;
      } else {  // Add the byte to the buffer if there's space
        if (bufferIndex < BUFFER_SIZE - 1) {
          incomingBuffer[bufferIndex++] = incomingByte;
        }
      }
    }
  }
}


This will give me "ON" and "RANGE xyz" where ON is giving the "presenence detected" (same as OT2_PIN) and xyz is giving the range at which the object was detected but its very unreliable so far.
Haven't tried so far with with the ld2410/2420 library again.

Anyhow, i ordererd a USB adapter for this sensor. I found some images showing a software to set up the sensor so it detects at the right range since setting it up in code seems a very tedious. Will try when the USB adapter arrives and post my results here.

I assume once setup is done correctly that the sensor can work without serial connection and I only need to read the OT2_PIN?

Ismaeelv
Posts: 1
Joined: Thu Mar 06, 2025 4:23 pm

Re: HLK LD2420

Postby Ismaeelv » Sat Oct 04, 2025 8:46 pm

Hi guys so I’m having a similar issue with the LD2420 module. Should I just include the HardwareSerial Library and then it should work fine right? Also is there no libraries for the ld2420 like there is for the ld2410. Also with regards to adjusting the region does that have to be done using the usb to TTL converter or can it be configured in the code. Your assistance would be much appreciated

Mauromm
Posts: 3
Joined: Tue Oct 14, 2025 10:19 pm

Re: HLK LD2420

Postby Mauromm » Tue Oct 14, 2025 10:39 pm

Hellow, I have the HLK-2420 working fine. I have two versions: one with ESP32 only and another one with ESP32 + SSD1306 display. I used the reference from: https://github.com/cyrixninja/LD2420.

Code: Select all

/*
 * BasicUsage.ino - Basic example for LD2420 Radar Sensor Library - ESP32 Version
 * 
 * This example demonstrates the basic usage of the LD2420 library on ESP32.
 * It shows how to initialize the sensor, read distance data, and use callbacks.
 * 
 * Hardware connections for ESP32:
 * - LD2420 VCC -> 3.3V
 * - LD2420 GND -> GND  
 * - LD2420 TX  -> Pin 16 (RX2)
 * - LD2420 RX  -> Pin 17 (TX2)
 * 
 * Author: cyrixninja
 * Date: July 22, 2025
 * Adapted for ESP32: [Mauro Miyashiro/DeepSeek]
 */

#include <HardwareSerial.h>
#include "LD2420.h"

// For ESP32, we can use HardwareSerial instead of SoftwareSerial
#define RX_PIN 16
#define TX_PIN 17

// Create HardwareSerial instance (UART2 on ESP32)
HardwareSerial sensorSerial(2);
LD2420 radar;

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  while (!Serial) {
    delay(10); // Wait for Serial Monitor
  }
  
  Serial.println("=== LD2420 Radar Sensor Example - ESP32 ===");
  
  // Initialize HardwareSerial for sensor communication
  sensorSerial.begin(115200, SERIAL_8N1, RX_PIN, TX_PIN);
  
  // Initialize the radar sensor
  if (radar.begin(sensorSerial)) {
    Serial.println("✓ LD2420 initialized successfully!");
    Serial.println(radar.getVersionInfo());
  } else {
    Serial.println("✗ Failed to initialize LD2420!");
    while (1) delay(1000); // Stop execution
  }
  
  // Configure distance range (optional)
  radar.setDistanceRange(0, 400); // 0-400 cm range
  
  // Set update interval (optional)
  radar.setUpdateInterval(50); // Update every 50ms
  
  // Set up callbacks (commented out if not available in your LD2420 library version)
  // radar.onDetection(onObjectDetected);
  // radar.onStateChange(onStateChanged);
  // radar.onDataUpdate(onDataReceived);
  
  Serial.println("Setup complete. Waiting for detections...");
  Serial.println("----------------------------------------");
}

void loop() {
  // Update the radar sensor (call this regularly)
  radar.update();
  
  // You can also read data directly
  if (radar.isDataValid()) {
    LD2420_Data data = radar.getCurrentData();
    
    // Print status every 2 seconds
    static unsigned long lastPrint = 0;
    if (millis() - lastPrint > 2000) {
      printStatus(data);
      lastPrint = millis();
    }
  }
  
  delay(10);
}

// Callback function called when an object is detected
void onObjectDetected(int distance) {
  Serial.print("🎯 Object detected at ");
  Serial.print(distance);
  Serial.println(" cm");
}

// Callback function called when detection state changes
void onStateChanged(LD2420_DetectionState oldState, LD2420_DetectionState newState) {
  Serial.print("📡 State change: ");
  Serial.print(stateToString(oldState));
  Serial.print(" -> ");
  Serial.println(stateToString(newState));
}

// Callback function called when new data is received
void onDataReceived(LD2420_Data data) {
  // This callback is called for every data update
  // You can use this for logging or processing all data
}

// Helper function to print current status
void printStatus(LD2420_Data data) {
  Serial.println("--- Current Status ---");
  Serial.print("Distance: ");
  Serial.print(data.distance);
  Serial.println(" cm");
  
  Serial.print("State: ");
  Serial.println(stateToString(data.state));
  
  Serial.print("Last update: ");
  Serial.print(millis() - data.timestamp);
  Serial.println(" ms ago");
  
  Serial.print("Data valid: ");
  Serial.println(data.isValid ? "Yes" : "No");
  Serial.println("---------------------");
}

// Helper function to convert state to string
String stateToString(LD2420_DetectionState state) {
  switch (state) {
    case LD2420_NO_DETECTION:
      return "No Detection";
    case LD2420_DETECTION_ACTIVE:
      return "Active Detection";
    case LD2420_DETECTION_LOST:
      return "Detection Lost";
    default:
      return "Unknown";
  }
}
     

Mauromm
Posts: 3
Joined: Tue Oct 14, 2025 10:19 pm

Re: HLK LD2420

Postby Mauromm » Tue Oct 14, 2025 10:47 pm

I have an improoved version of HLK-LD2420 running on ESP32 with SSD1306 display. It also has a diagnostic. I'm not a programmer (my expertise is hardware/IoT), so I had help form Artificial Inteligence.

Code: Select all

 /*
 * BasicUsage.ino - Basic example for LD2420 Radar Sensor Library - ESP32 Version
 * 
 * This example demonstrates the basic usage of the LD2420 library on ESP32.
 * It shows how to initialize the sensor, read distance data, and use callbacks.
 * 
 * Hardware connections for ESP32:
 * - LD2420 VCC -> 3.3V
 * - LD2420 GND -> GND  
 * - LD2420 TX  -> Pin 16 (RX2)
 * - LD2420 RX  -> Pin 17 (TX2)
 * - SSD1306 SDA -> GPIO 21
 * - SSD1306 SCL -> GPIO 22
 * 
 * Author: cyrixninja
 * Date: July 22, 2025
 * Adapted for ESP32: [Mauro Miyashiro/DeepSeek/Qwen]
 */

#include <HardwareSerial.h>
#include "LD2420.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// For ESP32, we can use HardwareSerial instead of SoftwareSerial
#define RX_PIN 16
#define TX_PIN 17

// OLED Display settings
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C

// Create HardwareSerial instance (UART2 on ESP32)
HardwareSerial sensorSerial(2);
LD2420 radar;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Variables for display update timing
unsigned long lastDisplayUpdate = 0;
const unsigned long DISPLAY_UPDATE_INTERVAL = 500; // Update display every 500ms

// Test variables
bool rxTestPassed = false;
bool txTestPassed = false;
bool communicationTested = false;

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  while (!Serial) {
    delay(10); // Wait for Serial Monitor
  }
  
  Serial.println("=== LD2420 Radar Sensor Example - ESP32 ===");
  
  // Initialize OLED display
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
  Serial.println("✓ SSD1306 display initialized!");
  
  // Display startup message
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(20,0);
  display.println("LD2420 Radar");
  display.setCursor(20,25);
  display.println("Inicializing...");
  display.display();
  delay(3000);
  
  // Initialize HardwareSerial for sensor communication
  sensorSerial.begin(115200, SERIAL_8N1, RX_PIN, TX_PIN);
  
  // Test radar sensor communication with RX/TX verification
  bool radarInitialized = initializeRadarWithTest();
  
  if (radarInitialized) {
    Serial.println("LD2420 initialized successfully!");
    Serial.println(radar.getVersionInfo());
    
    display.clearDisplay();
    display.setCursor(0,0);
    display.println("LD2420: OK");
    display.setCursor(0,20);
    display.println("RX: " + String(rxTestPassed ? "OK" : "FAIL"));
    display.setCursor(0,35);
    display.println("TX: " + String(txTestPassed ? "OK" : "FAIL"));
    display.display();
    delay(3000);
  } else {
    Serial.println("Failed to initialize LD2420!");
    
    display.clearDisplay();
    display.setCursor(0,0);
    display.println("LD2420: FAIL");
    display.setCursor(0,20);
    display.println("RX: " + String(rxTestPassed ? "OK" : "FAIL"));
    display.setCursor(0,35);
    display.println("TX: " + String(txTestPassed ? "OK" : "FAIL"));
    display.setCursor(0,50);
    display.println("Verify connections!");
    display.display();
    
    while (1) {
      delay(1000);
      // Blink display to indicate error
      display.invertDisplay(true);
      delay(500);
      display.invertDisplay(false);
      delay(500);
    }
  }
  
  // Configure distance range (optional)
  radar.setDistanceRange(0, 400); // 0-400 cm range
  
  // Set update interval (optional)
  radar.setUpdateInterval(50); // Update every 50ms
  
  Serial.println("Setup complete. Waiting for detections...");
  Serial.println("----------------------------------------");
  
  // Initial display setup
  updateDisplay("Testing...", "Waiting", 0, false);
}

bool initializeRadarWithTest() {
  Serial.println("Starting LD2420 communication...");
  
  // Test 1: Basic initialization
  display.clearDisplay();
  display.setCursor(0,0);
  display.println("Test LD2420:");
  display.setCursor(0,20);
  display.println("1. Initializing...");
  display.display();
  
  if (!radar.begin(sensorSerial)) {
    Serial.println("Basic initialization fail");
    return false;
  }
  Serial.println("Basic initializations is OK");
  delay(3000);
  
  // Test 2: RX Test - Check if we can read data from sensor
  display.clearDisplay();
  display.setCursor(0,0);
  display.println("Test LD2420:");
  display.setCursor(0,20);
  display.println("1. OK");
  display.setCursor(0,35);
  display.println("2. Test RX");
  display.display();
  
  rxTestPassed = testRXCommunication();
  Serial.println(rxTestPassed ? "RX test is OK" : "RX test fail");
  delay(3000);
  
  // Test 3: TX Test - Check if we can write commands to sensor
  display.clearDisplay();
  display.setCursor(0,0);
  display.println("Test LD2420:");
  display.setCursor(0,20);
  display.println("1. OK");
  display.setCursor(0,35);
  display.println("2. " + String(rxTestPassed ? "OK" : "FAIL"));
  display.setCursor(0,50);
  display.println("3. Test TX");
  display.display();
  
  txTestPassed = testTXCommunication();
  Serial.println(txTestPassed ? "Teste TX OK" : "Test TX FAIL");
  delay(3000);
  
  // Only proceed with data validation if both RX and TX are working
  bool dataTestPassed = false;
  if (rxTestPassed && txTestPassed) {
    // Test 4: Data validation test
    display.clearDisplay();
    display.setCursor(0,0);
    display.println("Test LD2420:");
    display.setCursor(0,20);
    display.println("1. OK");
    display.setCursor(0,30);
    display.println("2. " + String(rxTestPassed ? "OK" : "FAIL"));
    display.setCursor(0,40);
    display.println("3. " + String(txTestPassed ? "OK" : "FAIL"));
    display.setCursor(0,50);
    display.println("4. Validating dataset");
    display.display();
    
    dataTestPassed = testDataValidation();
    Serial.println(dataTestPassed ? "Test dataset is OK" : "Test dataset FAIL");
    delay(3000);
  } else {
    Serial.println("Sking test dataset - RX ou TX fail");
    dataTestPassed = false;
  }
  
  communicationTested = true;
  
  return rxTestPassed && txTestPassed && dataTestPassed;
}

bool testRXCommunication() {
  Serial.println("Testing comunication RX...");
  
  // First, check if we're receiving any data at all on the serial port
  Serial.println("checking dataset in the serial port...");
  
  int bytesAvailable = 0;
  for (int i = 0; i < 10; i++) {
    bytesAvailable = sensorSerial.available();
    if (bytesAvailable > 0) {
      Serial.println("Dataset detected in the serial port: " + String(bytesAvailable) + " bytes");
      break;
    }
    delay(100);
  }
  
  if (bytesAvailable == 0) {
    Serial.println("No dataset received in the serial port");
    return false;
  }
  
  // Try to read version info multiple times
  for (int i = 0; i < 5; i++) {
    String versionInfo = radar.getVersionInfo();
    if (versionInfo.length() > 0 && versionInfo != "Unknown") {
      Serial.println("RX OK: " + versionInfo);
      return true;
    }
    
    // Try to read basic data
    radar.update();
    delay(100);
    
    if (radar.isDataValid()) {
      LD2420_Data data = radar.getCurrentData();
      Serial.println("RX OK - Dataset received: " + String(data.distance) + "cm");
      return true;
    }
    
    delay(200);
  }
  
  return false;
}

bool testTXCommunication() {
  Serial.println("Testing omunication TX...");
  
  // Test 1: Check if we can reset the sensor configuration
  // This requires actual TX communication
  Serial.println("Test 1: Restarting configuration...");
  
  // Save current state
  bool hadValidDataBefore = radar.isDataValid();
  int previousDistance = 0;
  if (hadValidDataBefore) {
    LD2420_Data data = radar.getCurrentData();
    previousDistance = data.distance;
  }
  
  // Send reset command (change settings significantly)
  radar.setDistanceRange(20, 300); // Change range
  delay(200);
  radar.setUpdateInterval(100); // Change interval
  delay(200);
  
  // Now try to restore original settings
  radar.setDistanceRange(0, 400);
  delay(200);
  radar.setUpdateInterval(50);
  delay(200);
  
  // Test 2: Verify the sensor responds to our commands
  // by checking if we can still get data after configuration changes
  Serial.println("Test 2: Checking return from commands...");
  
  int successfulReads = 0;
  for (int i = 0; i < 8; i++) {
    radar.update();
    delay(150);
    
    if (radar.isDataValid()) {
      successfulReads++;
      LD2420_Data data = radar.getCurrentData();
      Serial.println("Leitura " + String(i+1) + ": " + String(data.distance) + "cm");
    }
    
    // If we get several successful reads, TX is working
    if (successfulReads >= 2) {
      Serial.println("TX OK - Sensor answer comands");
      return true;
    }
  }
  
  // Test 3: Alternative test - check if sensor stops responding when we send bad commands
  Serial.println("Test 3: Resiliance test...");
  
  // If we have RX working but no response to TX commands, TX might be broken
  if (rxTestPassed && successfulReads == 0) {
    Serial.println("TX FAIL - RX is working but no answer from comands");
    return false;
  }
  
  // If we get any successful reads, TX is working
  if (successfulReads > 0) {
    Serial.println("TX OK - " + String(successfulReads) + " valid reading");
    return true;
  }
  
  Serial.println("TX FAIL - No answer from comands");
  return false;
}

bool testDataValidation() {
  Serial.println("Validating dataset from sensor...");
  
  // Collect multiple data samples to validate
  int validSamples = 0;
  int totalSamples = 10;
  
  for (int i = 0; i < totalSamples; i++) {
    radar.update();
    delay(100);
    
    if (radar.isDataValid()) {
      LD2420_Data data = radar.getCurrentData();
      
      // Validate data ranges and consistency
      if (data.distance >= 0 && data.distance <= 400 && data.isValid) {
        validSamples++;
        Serial.println("Amostra " + String(i+1) + ": " + String(data.distance) + "cm - VALID");
      } else {
        Serial.println("Amostra " + String(i+1) + ": " + String(data.distance) + "cm - Out of range");
      }
    } else {
      Serial.println("Amostra " + String(i+1) + ": Invalid dataset");
    }
    
    delay(100);
  }
  
  // Consider test passed if we get at least 50% valid samples
  bool testPassed = (validSamples >= (totalSamples / 2));
  Serial.println("Valid samples: " + String(validSamples) + "/" + String(totalSamples));
  
  return testPassed;
}

void loop() {
  // Update the radar sensor (call this regularly)
  radar.update();
  
  // You can also read data directly
  if (radar.isDataValid()) {
    LD2420_Data data = radar.getCurrentData();
    
    // Print status every 2 seconds to Serial
    static unsigned long lastPrint = 0;
    if (millis() - lastPrint > 2000) {
      printStatus(data);
      lastPrint = millis();
    }
    
    // Update display more frequently (every 500ms)
    if (millis() - lastDisplayUpdate > DISPLAY_UPDATE_INTERVAL) {
      updateDisplayFromData(data);
      lastDisplayUpdate = millis();
    }
  } else {
    // No valid data available
    if (millis() - lastDisplayUpdate > DISPLAY_UPDATE_INTERVAL) {
      updateDisplay("No dataset", communicationTested ? "Verify sensor" : "Testing...", 0, false);
      lastDisplayUpdate = millis();
    }
  }
  
  delay(10);
}

// Update display with radar data
void updateDisplayFromData(LD2420_Data data) {
  String distanceStr = String(data.distance) + " cm";
  String stateStr = stateToString(data.state);
  
  updateDisplay(distanceStr, stateStr, data.distance, data.isValid);
}

// Main display update function
void updateDisplay(String distance, String state, int distanceValue, bool isValid) {
  display.clearDisplay();
  
  // Header
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("LD2420 Radar Sensor");
  
  // Distance information 
  display.setCursor(0, 16);
  display.setTextSize(1);
  display.print("Distance: ");
  display.println(distance);
  
  // State information
  display.setTextSize(1);
  display.setCursor(0, 29);
  display.print("Status: ");
  display.println(state);
  
  // Data validity and age
  display.setCursor(0, 41);
  display.print("Dataset: ");
  display.println(isValid ? "Valid" : "Invalid");
  
  // Visual indicator based on distance
  if (isValid && distanceValue > 0) {
    // Draw a simple radar-like visualization
    int indicatorWidth = map(constrain(distanceValue, 0, 400), 0, 400, 5, 120);
    display.fillRect(0, 55, indicatorWidth, 8, SSD1306_WHITE);
    
    // Add distance markers
    display.setCursor(0, 55);
    display.print("0");
    display.setCursor(120, 55);
    display.print("4m");
  }
  
  display.display();
}

// Helper function to print current status to Serial
void printStatus(LD2420_Data data) {
  Serial.println("--- Current Status ---");
  Serial.print("Distance: ");
  Serial.print(data.distance);
  Serial.println(" cm");
  
  Serial.print("State: ");
  Serial.println(stateToString(data.state));
  
  Serial.print("Last update: ");
  Serial.print(millis() - data.timestamp);
  Serial.println(" ms ago");
  
  Serial.print("Data valid: ");
  Serial.println(data.isValid ? "Yes" : "No");
  
  Serial.print("Communication: RX=");
  Serial.print(rxTestPassed ? "OK" : "FAIL");
  Serial.print(", TX=");
  Serial.println(txTestPassed ? "OK" : "FAIL");
  Serial.println("---------------------");
}

// Helper function to convert state to string
String stateToString(LD2420_DetectionState state) {
  switch (state) {
    case LD2420_NO_DETECTION:
      return "No detection";
    case LD2420_DETECTION_ACTIVE:
      return "Detection OK";
    case LD2420_DETECTION_LOST:
      return "Detection lost";
  default:
      return "Unknow";
  }
}  

Mauromm
Posts: 3
Joined: Tue Oct 14, 2025 10:19 pm

Re: HLK LD2420

Postby Mauromm » Tue Oct 14, 2025 10:51 pm

About HLK-LD2420, you can also try the software in this link: https://github.com/JoaoSandrini/LD2420-Radar.

Who is online

Users browsing this forum: Perplexity-User, Qwantbot and 3 guests