Example Code for Arduino-Read Detection Distance
The following tutorial will guide you through quickly using and acquiring sensor data on the Arduino platform, using the UNO R3 as an example.
Hardware Preparation
- DFRduino UNO R3 with IO Expansion Shield and USB Cable A-B (or similar) x 1
- 24GHz Human Presence Sensing Module × 1
- Connector × 1
Software Preparation
Wiring Diagram

| UNO R3 | PIN | Sensor | PIN |
|---|---|---|---|
| UNO R3 | VCC | Sensor | VCC |
| UNO R3 | GND | Sensor | GND |
| UNO R3 | Digital 3 | Sensor | UART_Rx |
| UNO R3 | Digital 2 | Sensor | UART_Tx |
Sample Code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); //定义软串口,3号端口为TX,2号端口为RX,
size_t readN(uint8_t *buf, size_t len);
bool recdData(uint8_t *buf);
uint8_t Cache[23] = {0}; //缓存
void setup()
{
Serial.begin(115200); //串口波特率
mySerial.begin(57600); //软串口
//Serial1.begin(256000);
}
void loop()
{
recdData(Cache);
}
size_t readN(uint8_t *buf, size_t len)
{
size_t offset = 0, left = len;
int16_t Tineout = 1500;
uint8_t *buffer = buf;
long curr = millis();
while (left) {
if (Serial1.available()) {
//buffer[offset] = Serial1.read();
buffer[offset] = Serial.read();
offset++;
left--;
}
if (millis() - curr > Tineout) {
break;
}
}
return offset;
}
bool recdData(uint8_t *buf)
{
int16_t Tineout = 50000;
long curr = millis();
uint8_t ch;
bool ret = false;
const char *P;
while (!ret) {
if (millis() - curr > Tineout) {
break;
}
if (readN(&ch, 1) == 1) {
if (ch == 0xF4) {
buf[0] = ch;
if (readN(&ch, 1) == 1) {
if (ch == 0xF3) {
buf[1] = ch;
if (readN(&ch, 1) == 1) {
if (ch == 0xF2) {
buf[2] = ch;
if (readN(&ch, 1) == 1) {
if (ch == 0xF1) {
buf[3] = ch;
if (readN(&buf[4], 19) == 19) {
// printdf(buf, 23); //打印原始数据
uint16_t Adistance = buf[10] << 8 | buf[9];
uint16_t Sdistance = buf[13] << 8 | buf[12];
uint16_t Distance = buf[16] << 8 | buf[15];
switch (buf[8]) {
case 0x00 : Serial.println("检测状态:无人"); break;
case 0x01 : Serial.println("检测状态:运动"); break;
case 0x02 : Serial.println("检测状态:静止"); break;
case 0x03 : Serial.println("检测状态:运动&静止目标"); break;
}
// Serial.print("运动目标能量值:");
// Serial.println(buf[11]);
// Serial.print("静止目标能量值:");
// Serial.println(buf[14]);
// Serial.print("运动目标距离CM:");
// Serial.println(Adistance);
// Serial.print("静止目标距离CM:");
// Serial.println(Sdistance);
Serial.print("探测距离CM:");
Serial.println(Distance);
break;
}
}
}
}
}
}
}
}
}
}
return ret;
}
void printdf(uint8_t *buf, int len)
{
for (int i = 0; i < len; i++) {
if (buf[i] < 0x10) {
Serial.print("0");
}
Serial.print(buf[i], HEX);
Serial.print(" ");
}
Serial.println();
}
Result
The module only outputs the target distance value of the moving state, and the distance value of the non-moving state is 0.For details, please refer to the serial communication protocol description.

Was this article helpful?
