Interrupt handler question

I have a project on the go where I am using all 6 interrupts on an Arduino Mega. I currently use the following code to attach the interrupts:

attachInterrupt(0, Counter0Handler, RISING);
attachInterrupt(1, Counter1Handler, RISING);
attachInterrupt(2, Counter2Handler, RISING);
attachInterrupt(3, Counter3Handler, RISING);
attachInterrupt(4, Counter4Handler, RISING);
attachInterrupt(5, Counter5Handler, RISING);

I was wondering if I could handle all 6 interrupts using a single function by using something like:

attachInterrupt(0, CounterHandler(0), RISING);

I have tried it but to no avail. Is there a way of doing this?

Z

Here's the definition of attachInterrupt: void attachInterrupt(uint8_t, void (*)(void), int mode);

No, you can't do it this way, because attach interrupt expects a pointer to a function with no parameter and no return value. In your example. you passed the return value the function call CounterHandler(0), which most likely isn't a function pointer.

What you can do is write bunch of stubs which call your function in turn with the proper parameter. In many languages that can be done with dynamic or lambda functions, but to my knowledge not in C.

inline void Counter0Handler () {
CounterHandler(0);
}

Korman

It would not be too difficult to create your own variant of WInterrupts.c that passed back the interrupt number to the interrupt handler function...

Something like:

void attachInterrupt( uint8_t interruptNum, void ( *userFunc )( int ), int mode )
{
...
}

You can see the userFunc is now a fp that takes an integer parameter, so then the ISR simply passes the interrupt number - something like:

SIGNAL( INT0_vect )
{
if ( intFunc[ EXTERNAL_INT_0 ] )
intFunc EXTERNAL_INT_0 ;
}

and so on for the rest of the ISR's..

So you could then call from your sketch in this manner:

attachInterrupt( 0, CounterHandler, RISING );

and CounterHandler would be:

void CounterHandler( int interruptID )
{
...
}

Of course in this form you'd break compatibility with the existing functionality, which might not be a problem in your case...

Cheers,