Arduino library interruptions

I am creating a library for an energy meter. I want to count the pulses that the energy meter produces and convert them to energy through arduino. To catch any impulse, I want to use arduino interrupts. I want this to be easy to use:

#include <EnergyCounter.h>

#define counterPin 2; // interrupt code 0 in Uno
EnergyCounter counter;

void setup(){
    counter.begin(counterPin);
}
...

Now, inside the begin method, I want to bind an interrupt to counterPin:

void EnergyCounter::begin(byte pin){
    pinMode(pin, INPUT);
    attachInterrupt(0, countPulse, RISING);
}

void EnergyCounter::countPulse(){
    display += increment_per_pulse;
}

When I try, I get the following error:

error: cannot convert 'EnergyCounter::countPulse' from type 'void (EnergyCounter::)()' to type 'void (*)()'
 attachInterrupt(0, countPulse, RISING);
                                      ^
Erro ao compilar.

Does this mean that I cannot use the method as an interrupt service routine (ISR)? How can I solve the problem and still have an easy to use interface for the library?

+4
source share
2 answers

increment_per_pulse must be a static function (see signature).

, static:

static void increment_per_pulse();
+1

EnergyCounter countPulse , :

class EnergyCounter{
   //...
   static void countPulse();
   //...
};

: ISR , void . () , .

- countPulse EnergyCounter ( - ).

+1

Source: https://habr.com/ru/post/1615209/


All Articles