101 lines
2.7 KiB
C++
101 lines
2.7 KiB
C++
#ifndef IR_RECEIVER_H
|
|
#define IR_RECEIVER_H
|
|
|
|
#include <Arduino.h>
|
|
#include <IRremote.h>
|
|
|
|
// 红外接收结果结构体
|
|
struct IRReceiveResult {
|
|
bool success; // 是否成功接收到信号
|
|
uint32_t protocol; // 协议类型
|
|
uint32_t address; // 地址码
|
|
uint32_t command; // 命令码
|
|
uint16_t bits; // 数据位数
|
|
uint16_t* rawData; // 原始数据指针
|
|
size_t rawLength; // 原始数据长度
|
|
};
|
|
|
|
class IRReceiver {
|
|
private:
|
|
static uint8_t receivePin;
|
|
static bool initialized;
|
|
static uint16_t rawBuffer[RAW_BUFFER_LENGTH];
|
|
|
|
public:
|
|
// 初始化红外接收器
|
|
static void init(uint8_t pin = 15);
|
|
|
|
// 读取红外信号直到信号结束,返回读取结果
|
|
static IRReceiveResult readIRSignal(uint32_t timeoutMs = 5000);
|
|
|
|
// 释放资源
|
|
static void cleanup();
|
|
};
|
|
|
|
// 静态成员变量定义
|
|
uint8_t IRReceiver::receivePin = 15;
|
|
bool IRReceiver::initialized = false;
|
|
uint16_t IRReceiver::rawBuffer[RAW_BUFFER_LENGTH];
|
|
|
|
// 初始化红外接收器
|
|
void IRReceiver::init(uint8_t pin) {
|
|
receivePin = pin;
|
|
IrReceiver.begin(receivePin, ENABLE_LED_FEEDBACK);
|
|
initialized = true;
|
|
}
|
|
|
|
// 读取红外信号直到信号结束,返回读取结果
|
|
IRReceiveResult IRReceiver::readIRSignal(uint32_t timeoutMs) {
|
|
IRReceiveResult result = {false, 0, 0, 0, 0, nullptr, 0};
|
|
|
|
if (!initialized) {
|
|
return result;
|
|
}
|
|
|
|
unsigned long startTime = millis();
|
|
|
|
// 等待接收到红外信号
|
|
while (!IrReceiver.decode()) {
|
|
if (millis() - startTime > timeoutMs) {
|
|
return result; // 超时返回失败结果
|
|
}
|
|
delay(1);
|
|
}
|
|
|
|
// 成功接收到信号
|
|
result.success = true;
|
|
result.protocol = IrReceiver.decodedIRData.protocol;
|
|
result.address = IrReceiver.decodedIRData.address;
|
|
result.command = IrReceiver.decodedIRData.command;
|
|
result.bits = IrReceiver.decodedIRData.numberOfBits;
|
|
|
|
// 复制原始数据到缓冲区
|
|
if (IrReceiver.decodedIRData.rawDataPtr != nullptr) {
|
|
result.rawLength = IrReceiver.decodedIRData.rawlen;
|
|
// 确保不超过缓冲区大小
|
|
if (result.rawLength > RAW_BUFFER_LENGTH) {
|
|
result.rawLength = RAW_BUFFER_LENGTH;
|
|
}
|
|
|
|
// 复制原始数据
|
|
for (size_t i = 0; i < result.rawLength; i++) {
|
|
rawBuffer[i] = IrReceiver.decodedIRData.rawDataPtr->rawbuf[i];
|
|
}
|
|
result.rawData = rawBuffer;
|
|
}
|
|
|
|
// 准备接收下一个信号
|
|
IrReceiver.resume();
|
|
|
|
return result;
|
|
}
|
|
|
|
// 释放资源
|
|
void IRReceiver::cleanup() {
|
|
if (initialized) {
|
|
IrReceiver.stop();
|
|
initialized = false;
|
|
}
|
|
}
|
|
|
|
#endif |