本帖最后由 iufly 于 2024-3-22 18:58 编辑
使用ESP32作为主控,RD-03E雷达的TX引脚连接GPIO16,RX连接GPIO17,在有人的模式下GPIO2输出高电平,没有人的情况下输出低电平。为防止误报,如果持续5秒检测到没人或者有人,对应的状态才会改变。源码如下:
// 定义常量
const byte START_BYTE1 = 0xAA;
const byte START_BYTE2 = 0xAA;
const byte PACKET_SIZE = 7; // 数据包大小
const byte TARGET_STATE_INDEX = 2; // 目标状态索引
const byte DISTANCE_INDEX_MSB = 3; // 距离高位索引
const byte DISTANCE_INDEX_LSB = 4; // 距离低位索引
const byte END_BYTE1 = 0x55;
const byte END_BYTE2 = 0x55;
const byte LED_PIN = 2; // LED pin
// 存储接收到的数据
byte receivedData[PACKET_SIZE];
byte dataIndex = 0;
bool dataAvailable = false;
bool lastTargetState = false; // 上一个目标状态
unsigned long lastChangeTime = 0; // 上一次状态改变的时间
unsigned long debounceDelay = 5000; // 抖动延迟时间,单位毫秒
void processPacket();
void setup() {
Serial.begin(115200); // 使用Serial发送数据,波特率为115200
Serial2.begin(256000); // 使用Serial2接收数据,波特率为256000
pinMode(LED_PIN, OUTPUT); // 将LED_PIN设置为输出模式
}
void loop() {
// 接收数据
if (Serial2.available() > 0) {
byte receivedByte = Serial2.read();
// 检查开始字节
if (dataIndex == 0 && receivedByte == START_BYTE1) {
receivedData[dataIndex++] = receivedByte;
} else if (dataIndex == 1 && receivedByte == START_BYTE2) {
receivedData[dataIndex++] = receivedByte;
} else if (dataIndex > 1 && dataIndex < PACKET_SIZE - 2) { // 读取数据部分
receivedData[dataIndex++] = receivedByte;
} else if (dataIndex == PACKET_SIZE - 2 && receivedByte == END_BYTE1) { // 检查结束字节
receivedData[dataIndex++] = receivedByte;
} else if (dataIndex == PACKET_SIZE - 1 && receivedByte == END_BYTE2) {
receivedData[dataIndex++] = receivedByte;
dataAvailable = true;
} else {
// 如果接收到的字节不符合预期,则重置索引
dataIndex = 0;
}
}
// 如果有完整的数据包可用,则处理它
if (dataAvailable) {
processPacket();
dataAvailable = false;
dataIndex = 0;
}
}
// 处理接收到的数据包
void processPacket() {
// 解析目标状态
byte targetState = receivedData[TARGET_STATE_INDEX];
// 解析距离(将高位和低位合并)
unsigned int distance = (receivedData[DISTANCE_INDEX_MSB] << 8) | receivedData[DISTANCE_INDEX_LSB];
// 状态改变后一定时间内不改变状态
if (targetState != lastTargetState && millis() - lastChangeTime >= debounceDelay) {
lastTargetState = targetState;
lastChangeTime = millis();
// 根据目标状态设置 LED 的输出状态
if (targetState == 0x00) {
digitalWrite(LED_PIN, LOW); // 无目标,LED 熄灭
} else {
digitalWrite(LED_PIN, HIGH); // 有目标,LED 亮起
}
}
// 输出解析结果
Serial.print("Target State: ");
Serial.println(targetState, HEX);
Serial.print("Distance: ");
Serial.println(distance);
}
sketch_mar22a.zip
(1.3 KB, 下载次数: 4)
|