Is there a way to use PCNT on the ESP32 under the Arduino IDE? I can find it for the Espressif IDF, but I haven't been able to find a way to use it yet under Arduino.
Did you find any example? I see a pcnt.h file in arduino core:
https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/include/driver/driver/pcnt.h
Maybe we can "merge" these two snippets into an ESP32-working source:
OpenEnergyMonitor Arduino pulse counter:
//Number of pulses, used to measure energy.
long pulseCount = 0;
//Used to measure power.
unsigned long pulseTime,lastTime;
//power and energy
double power, elapsedkWh;
//Number of pulses per wh - found or set on the meter.
int ppwh = 1; //1000 pulses/kwh = 1 pulse per wh
void setup()
{
Serial.begin(115200);
// KWH interrupt attached to IRQ 1 = pin3
attachInterrupt(1, onPulse, FALLING);
}
void loop()
{
}
// The interrupt routine
void onPulse()
{
//used to measure time between pulses.
lastTime = pulseTime;
pulseTime = micros();
//pulseCounter
pulseCount++;
//Calculate power
power = (3600000000.0 / (pulseTime - lastTime))/ppwh;
//Find kwh elapsed
elapsedkWh = (1.0*pulseCount/(ppwh*1000)); //multiply by 1000 to convert pulses per wh to kwh
//Print the values.
Serial.print(power,4);
Serial.print(" ");
Serial.println(elapsedkWh,3);
}
ESP32 GPIO interrupt manager:
#include <Arduino.h>
struct Button {
const uint8_t PIN;
uint32_t numberKeyPresses;
bool pressed;
};
Button button1 = {23, 0, false};
Button button2 = {18, 0, false};
void IRAM_ATTR isr(void* arg) {
Button* s = static_cast<Button*>(arg);
s->numberKeyPresses += 1;
s->pressed = true;
}
void IRAM_ATTR isr() {
button2.numberKeyPresses += 1;
button2.pressed = true;
}
void setup() {
Serial.begin(115200);
pinMode(button1.PIN, INPUT_PULLUP);
attachInterruptArg(button1.PIN, isr, &button1, FALLING);
pinMode(button2.PIN, INPUT_PULLUP);
attachInterrupt(button2.PIN, isr, FALLING);
}
void loop() {
if (button1.pressed) {
Serial.printf("Button 1 has been pressed %u times\n", button1.numberKeyPresses);
button1.pressed = false;
}
if (button2.pressed) {
Serial.printf("Button 2 has been pressed %u times\n", button2.numberKeyPresses);
button2.pressed = false;
}
static uint32_t lastMillis = 0;
if (millis() - lastMillis > 10000) {
lastMillis = millis();
detachInterrupt(button1.PIN);
}
}