How to use attachInterrupt with a class member

C guru I need you! I'm trying to write a library for some basic motor control, and I'm using interrupts to process the pulses from the reed switches on the motors I'm using. The problem I'm having is that the attachInterrupt() function doesn't like to receive my class member function pointer. The compiler spits out the following error:

Motor.cpp:32: error: argument of type 'void (Motor::)()' does not match 'void (*)()'

this is in response to a line in my class constructor making the following call: attachInterrupt(0, motor1Feedback,RISING);

the declaration for my interrupt handler (which I declared as a private class member function) looks like: void Motor::motor1Feedback()

I had thought I had read somewhere that what you wanted to do is not possible.

I then found this: http://www.mail-archive.com/avr-libc-dev@nongnu.org/msg02454.html

It might be helpful to you but is not Arduino specific, so it may not be appropriate.

--Phil.

As a quick hack I usually make a wrapper function at global scope.

Typically:

class Foo{
  public:
    void bar();
};

Foo foo;

void setup(){
  attachInterrupt(0,fooBar,RISING);
}

void loop(){}

void fooBar(){
  foo.bar();
}

I wrote this in another thread, not too long ago:

Class member functions that appear to take no arguments actually do take an invisible argument called this. The value of this is the instance of the object you're referring to. You can't attachInterrupt() to a class member function directly. You might be able to do it if the member function is static, but my approach is to have a global variable that is the instance, and the global service routine knows how to use the global variable.

MyClass theInstance = NULL;

// Somewhere, fill in an initialized copy of MyClass,
// and set theInstance to it.

ISR(TIMER1_0VF_vect)
{
    if (theInstance)
        theInstance->handleInterrupt();
}

If you do want to try to connect a static class member function to an interrupt vector, you should find the real definition of the ISR() macro, and try to adapt it into a CLASS_ISR() for the static class technique, like follower's page does. I think it might be a little different from the page shown, but it is on an avr development list so it's probably close.

Thanks everyone. I know why there are lots of stars next to all of your names!

Follower - great link, it will take a little work for me to convert that to Aurduino interrupts

AlphaBeta - oh the beauty of a quick hack....

Halley - Om. I will meditate on the meaning of all this while facing towards you.