2 #error Only supports ESP32
11 #include "driver/rmt.h"
12 #include "esp32-hal.h"
15 #define RMT_RX_MODE false
21 PWMDecoder(
void (*changeNotify)(
int pin, uint16_t pwm),
int pin1,
int pin2 = -1,
int pin3 = -1,
int pin4 = -1) :
22 fChangeNotify(changeNotify)
24 fChannel[0].fGPIO = uint8_t(pin1);
25 fChannel[1].fGPIO = uint8_t(pin2);
26 fChannel[2].fGPIO = uint8_t(pin3);
27 fChannel[3].fGPIO = uint8_t(pin4);
37 PWMDecoder(
int pin1,
int pin2 = -1,
int pin3 = -1,
int pin4 = -1) :
42 inline uint16_t
channel(
unsigned i = 0)
const
44 return fChannel[i].fRawPulse;
49 return fChannel[i].fRawPulse;
54 return abs(int32_t(fChannel[i].fPulse) - int32_t(fChannel[i].fRawPulse)) > 20;
64 return millis() - fChannel[i].fLastActive;
69 return millis() > 500 && (fChannel[i].fPulse != 0 &&
getAge(i) < 500);
74 return (fChannel[i].fAliveStateChange && fChannel[i].fAlive);
79 return (fChannel[i].fAliveStateChange && !fChannel[i].fAlive);
84 for (
unsigned i = 0; i < fNumChannels; i++)
91 fChannel[i].fPulse = fChannel[i].fRawPulse;
92 if (fChangeNotify !=
nullptr)
93 fChangeNotify(fChannel[i].fGPIO, fChannel[i].fPulse);
95 fChannel[i].fAliveStateChange =
false;
98 if (!fChannel[i].fAlive)
101 fChannel[i].fAlive =
true;
102 fChannel[i].fAliveStateChange =
true;
105 else if (fChannel[i].fAlive)
108 fChannel[i].fAlive =
false;
109 fChannel[i].fAliveStateChange =
true;
120 for (
unsigned i = 0; i < fNumChannels; i++)
122 if ((fChannel[i].fReceiver = rmtInit(fChannel[i].fGPIO,
RMT_RX_MODE, RMT_MEM_64)) != NULL)
124 rmtSetTick(fChannel[i].fReceiver, 1000);
125 rmtSetFilter(fChannel[i].fReceiver,
true, 100);
126 rmtSetRxThreshold(fChannel[i].fReceiver, 5000);
127 rmtRead(fChannel[i].fReceiver, receive_data, &fChannel[i]);
142 for (
unsigned i = 0; i < fNumChannels; i++)
144 if (fChannel[i].fReceiver !=
nullptr)
146 rmtEnd(fChannel[i].fReceiver);
147 rmtDeinit(fChannel[i].fReceiver);
148 fChannel[i].fReceiver =
nullptr;
159 uint8_t fNumChannels = 1;
160 static constexpr
unsigned fMaxChannels = 8;
165 volatile uint16_t fRawPulse;
167 bool fAliveStateChange;
168 uint32_t fLastActive;
169 rmt_obj_t* fReceiver;
170 } fChannel[fMaxChannels] = {};
171 void (*fChangeNotify)(
int pin, uint16_t pwm) =
nullptr;
174 static void receive_data(uint32_t* data,
size_t len,
void* arg)
176 Channel*
channel = (Channel*)arg;
177 rmt_data_t* it = (rmt_data_t*)data;
180 channel->fRawPulse = it[0].duration0;
181 channel->fLastActive = millis();
185 rmt_isr_handle_t fISRHandle =
nullptr;
186 static void IRAM_ATTR rmt_isr_handler(
void* arg);
187 void checkActive(
unsigned i);
191 #define ServoDecoder PWMDecoder