LD2410Async
Asynchronous Arduino ESP32 library for the LD2410 mmWave radar sensor
Loading...
Searching...
No Matches
enableConfigModeTest.ino
Go to the documentation of this file.
1/**
2 * @file measureEnableConfigMode.ino
3 * @brief
4 * Test sketch for LD2410Async library to evaluate the execution time
5 * of the enableConfigModeAsync() command.
6 *
7 * @details
8 * This sketch continuously executes a measurement sequence:
9 * - Calls enableConfigModeAsync() and measures how long it takes until
10 * the ACK (callback) is triggered.
11 * - Once config mode is enabled, executes one randomly chosen command
12 * (requestDistanceResolutionAsync, requestAuxControlSettingsAsync,
13 * requestAllConfigSettingsAsync, requestAllStaticDataAsync,
14 * requestFirmwareAsync, or no command at all).
15 * - Calls disableConfigModeAsync().
16 * - Waits a random timespan between 1–5000 ms using the Ticker library.
17 * - Repeats the sequence indefinitely.
18 *
19 * The sketch prints the minimum, maximum, average, and count of all
20 * measurements after each test cycle.
21 */
22
23#include <Arduino.h>
24#include <Ticker.h>
25#include "LD2410Async.h"
26
27 // ========================= USER CONFIGURATION =========================
28
29#define RADAR_RX_PIN 32 ///< ESP32 pin receiving data from the radar (radar TX)
30#define RADAR_TX_PIN 33 ///< ESP32 pin transmitting data to the radar (radar RX)
31#define RADAR_BAUDRATE 256000 ///< UART baudrate for radar sensor (default is 256000)
32#define LED_PIN 2 ///< GPIO for internal LED (adjust if needed)
33// ======================================================================
34// Global objects
35// ======================================================================
36
37HardwareSerial RadarSerial(1); ///< HardwareSerial instance bound to UART1
38LD2410Async ld2410(RadarSerial); ///< LD2410Async driver instance
39Ticker delayTicker; ///< Ticker for randomized delays
40
41// ======================================================================
42// Measurement variables
43// ======================================================================
44
45unsigned long enableStartMs = 0; ///< Timestamp when enableConfigModeAsync() was called
46unsigned long minEnableDurationMs = ULONG_MAX; ///< Minimum execution time measured so far
47unsigned long maxEnableDurationMs = 0; ///< Maximum execution time measured so far
48unsigned long totalEnableDurationMs = 0; ///< Sum of all measured durations
49unsigned long measurementCount = 0; ///< Number of successful measurements
50unsigned long failureCount = 0; ///< Number of failed measurements
51unsigned long delayMs = 0; ///< Delay before the tests
52unsigned long dataCount = 0; ///< Used to count received data frames
53// ======================================================================
54// Forward declarations of callbacks
55// ======================================================================
56
60
61
62// ======================================================================
63// Utility functions
64// ======================================================================
65
66/**
67 * @brief Print a number padded to 6 characters width.
68 *
69 * @param value Number to print
70 */
71void printPaddedNumber(unsigned long value) {
72 char buf[8];
73 snprintf(buf, sizeof(buf), "%6lu", value);
74 Serial.print(buf);
75}
76
77/**
78 * @brief Convert AsyncCommandResult enum to human-readable text.
79 *
80 * @param result Enum value from LD2410Async
81 * @return const char* String representation
82 */
84 switch (result) {
85 case LD2410Async::AsyncCommandResult::SUCCESS: return "SUCCESS";
86 case LD2410Async::AsyncCommandResult::FAILED: return "FAILED";
87 case LD2410Async::AsyncCommandResult::TIMEOUT: return "TIMEOUT";
88 case LD2410Async::AsyncCommandResult::CANCELED: return "CANCELED";
89 default: return "UNKNOWN";
90 }
91}
92
93// ======================================================================
94// Test sequence functions
95// ======================================================================
96
97/**
98 * @brief Schedule the next test sequence.
99 *
100 * Waits a random time between 1–5000 ms before calling enableConfigModeAsync().
101 */
103 dataCount = 0;
104
105 switch (random(0, 4)) {
106 case 0:
107 delayMs = random(1, 11);
108 break;
109 case 1:
110 delayMs = random(1, 11) * 10;;
111 break;
112 case 2:
113 delayMs = random(0, 50) * 20 + 100;
114 break;
115 default:
116 delayMs = random(0, 70) * 100 + 1000;
117 break;
118 }
119
121
122 Serial.print("Test ");
124 Serial.print(" | Delay: ");
126
127
128 delayTicker.once_ms(delayMs, []() {
129 Serial.print(" (Data cnt: ");
131 Serial.print(")");
132 enableStartMs = millis();
133 dataCount = 0;
135 Serial.println(" > enableConfigModeAsync could not be started (busy).");
136 failureCount++;
138 }
139 else {
140 Serial.print(" > ");
141 }
142 });
143}
144
145/**
146 * @brief Callback for enableConfigModeAsync().
147 *
148 * Updates statistics, prints results and triggers an extra command.
149 *
150 * @param sender Pointer to the LD2410Async instance
151 * @param result Result of the command
152 */
154 unsigned long duration = millis() - enableStartMs;
155
157 totalEnableDurationMs += duration;
158 if (duration > maxEnableDurationMs) maxEnableDurationMs = duration;
159 if (duration < minEnableDurationMs) minEnableDurationMs = duration;
160
161 unsigned long avg = totalEnableDurationMs / measurementCount;
162
163
164 Serial.print("Dur: ");
165 printPaddedNumber(duration);
166 Serial.print(" ms | Data Cnt:");
168 Serial.print(" | Min: ");
170 Serial.print(" ms | Max: ");
172 Serial.print(" ms | Avg: ");
174 Serial.print(" ms | Fails: ");
176 Serial.println();
177
178 // Execute a random extra command
179 int cmd = random(0, 6);
180 switch (cmd) {
186 case 5: // No extra command
188 Serial.println("Could not start disableConfigMode()");
190 }
191 break;
192 }
193 }
194 else {
195 Serial.print("enableConfigModeAsync failed: ");
196 Serial.print(resultToString(result));
197 Serial.print(" Received ");
199 Serial.println(" data frames while waiting for ACK");
200 failureCount++;
203 }
204}
205
206/**
207 * @brief Callback for extra commands.
208 *
209 * @param sender Pointer to the LD2410Async instance
210 * @param result Result of the command
211 */
214 Serial.print("Extra command failed ");
215 Serial.println(resultToString(result));
216 }
218 Serial.println("Could not start disableConfigMode()");
220 }
221}
222
223/**
224 * @brief Callback for disableConfigModeAsync().
225 *
226 * Once config mode is disabled, schedules the next test sequence.
227 *
228 * @param sender Pointer to the LD2410Async instance
229 * @param result Result of the command
230 */
233 Serial.print("Disable config mode failed ");
234 Serial.println(resultToString(result));
235 }
237}
238
239// ======================================================================
240// Callback function
241// ======================================================================
242
243/**
244 * @brief Callback triggered when new detection data is received.
245 *
246 * @param sender Pointer to the LD2410Async instance
247 * @param presenceDetected Convenience flag for presence detection
248 */
249void onDetectionDataReceived(LD2410Async* sender, bool presenceDetected) {
250 // Toggle LED whenever data arrives
251 int currentState = digitalRead(LED_PIN);
252 digitalWrite(LED_PIN, currentState == HIGH ? LOW : HIGH);
253
254 //Count data frames
255 dataCount++;
256}
257// ======================================================================
258// Setup and loop
259// ======================================================================
260
261/**
262 * @brief Arduino setup function.
263 *
264 * Initializes Serial, the radar UART, and the LD2410Async library.
265 * Starts the first test sequence by calling scheduleNextSequence().
266 */
267void setup() {
268 Serial.begin(115200);
269 delay(2000);
270 Serial.println("=== LD2410Async enableConfigModeAsync measurement test ===");
271
272 pinMode(LED_PIN, OUTPUT);
273 digitalWrite(LED_PIN, LOW);
274
276
277 if (!ld2410.begin()) {
278 Serial.println("Failed to start LD2410Async task!");
279 while (true) delay(1000);
280 }
281 else {
282 Serial.println("LD2410Async task started!");
283
284 //Callback reghistration can take place at any time
286 }
287
288 // Long timeout to ensure that we can really measure the actual execution time
290
291 // Kick off the very first sequence
293}
294
295/**
296 * @brief Arduino loop function.
297 *
298 * Empty because everything is event-driven using callbacks and ticker.
299 */
300void loop() {
301 delay(1000); // idle delay
302}
Asynchronous driver class for the LD2410 human presence radar sensor.
Definition LD2410Async.h:38
bool begin()
Starts the background task that continuously reads data from the sensor.
AsyncCommandResult
Result of an asynchronous command execution.
Definition LD2410Async.h:47
@ TIMEOUT
No ACK received within the expected time window.
@ FAILED
Command failed (sensor responded with negative ACK).
@ SUCCESS
Command completed successfully and ACK was received.
@ CANCELED
Command was canceled by the user before completion.
bool requestAllStaticDataAsync(AsyncCommandCallback callback)
Requests all static information from the sensor.
bool disableConfigModeAsync(AsyncCommandCallback callback)
Disables config mode on the radar.
bool enableConfigModeAsync(AsyncCommandCallback callback)
Enables config mode on the radar.
void setAsyncCommandTimeoutMs(unsigned long timeoutMs)
Sets the timeout for async command callbacks.
bool requestDistanceResolutionAsync(AsyncCommandCallback callback)
Requests the current distance resolution setting from the sensor.
bool requestFirmwareAsync(AsyncCommandCallback callback)
Requests the firmware version of the sensor.
bool requestAllConfigSettingsAsync(AsyncCommandCallback callback)
Requests all configuration settings from the sensor.
bool requestAuxControlSettingsAsync(AsyncCommandCallback callback)
Requests the current auxiliary control settings.
void onDetectionDataReceived(DetectionDataCallback callback)
Registers a callback for new detection data.
unsigned long failureCount
Number of failed measurements.
const char * resultToString(LD2410Async::AsyncCommandResult result)
Convert AsyncCommandResult enum to human-readable text.
HardwareSerial RadarSerial(1)
HardwareSerial instance bound to UART1.
void setup()
Arduino setup function.
unsigned long delayMs
Delay before the tests.
void onDetectionDataReceived(LD2410Async *sender, bool presenceDetected)
Callback triggered when new detection data is received.
unsigned long measurementCount
Number of successful measurements.
void disableConfigModeCallback(LD2410Async *sender, LD2410Async::AsyncCommandResult result)
Callback for disableConfigModeAsync().
void enableConfigModeCallback(LD2410Async *sender, LD2410Async::AsyncCommandResult result)
Callback for enableConfigModeAsync().
#define RADAR_BAUDRATE
UART baudrate for radar sensor (default is 256000)
#define RADAR_RX_PIN
ESP32 pin receiving data from the radar (radar TX)
unsigned long enableStartMs
Timestamp when enableConfigModeAsync() was called.
LD2410Async ld2410(RadarSerial)
LD2410Async driver instance.
unsigned long maxEnableDurationMs
Maximum execution time measured so far.
Ticker delayTicker
Ticker for randomized delays.
#define LED_PIN
GPIO for internal LED (adjust if needed)
unsigned long totalEnableDurationMs
Sum of all measured durations.
void printPaddedNumber(unsigned long value)
Print a number padded to 6 characters width.
unsigned long minEnableDurationMs
Minimum execution time measured so far.
#define RADAR_TX_PIN
ESP32 pin transmitting data to the radar (radar RX)
void extraCommandCallback(LD2410Async *sender, LD2410Async::AsyncCommandResult result)
Callback for extra commands.
void scheduleNextSequence()
Schedule the next test sequence.
unsigned long dataCount
Used to count received data frames.
void loop()
Arduino loop function.