How to write multiple attachInterrupt functions in a for loop

Hi I am trying to set up several attchInterrupt functions (with ESP32).

For example,

attachInterrupt( PIN[0], isr1, RISING);
attachInterrupt( PIN[1], isr2, RISING);
attachInterrupt( PIN[2], isr3, RISING);
attachInterrupt( PIN[3], isr4, RISING);

I am thinking to write something like this,

for(int i=0; i<4; i++){
    attachInterrupt( PIN[i], isr???, RISING);
}

but can't figure out how to pass a variable to name the interrupt service routines. Is there a better way to write repeated attachInterrupt functions? Thanks!

Use an array of function pointers, indexed by the loop variable.

What do you imagine you gain by doing that? It will likely compile to LARGER code, use more RAM, and run slower. Fewer lines of source code does not necessarily mean less code after compilation, or faster code.

I might end up using 16 attachInterrupt functions on my ESP32 project, so am thinking a better way to write the code. It will save me time down the road if I have to modify the code.

Could you please provide me an example code? or point me where I can look up the method you mention? thanks!!

Why? Is a few lines of source code such a big deal?

Hello,

You can do like this

void (*isrList[])() = { isr1, isr2, ... };
...
attachInterrupt( PIN[i], isrList[i], RISING);

Thank you! That's very helpful!

If you're uncertain how many interrupts you'll be using in the final sketch, a loop like that is a good way to minimize the amount of modifications you need to do to add another interrupt. There are some other optimizations you can do.

For starters, make the computer work for you. Instead of hardcoding that you have 4 elements in the array (which requires manual editing if you change the size of the array), you can use a macro function like #define ARRAY_LENGTH(x) (sizeof(x)/sizeof(x[0])) to make the computer keep track of how much stiff you have in the array.

The other thing you can do is combine both the pin and the ISR pointer into a single data type using a struct. Then just make an array of those structs to hold the pin/function pairs.

Combine the two things and you get this:

#define ARRAY_LENGTH(x) (sizeof(x)/sizeof(x[0]))
typedef void (*isr_callback)();
struct hardware_interrupt
{
  uint8_t pin_no;
  isr_callback isr;
};

void isr1(){}
void isr2(){}
void isr3(){}

hardware_interrupt isrArray[] = 
{
  {1, isr1},
  {2, isr2},
  {3, isr3}
};

void setup()
{
  for( int i=0; i<ARRAY_LENGTH(isrArray); ++i)
  {
    attachInterrupt(isrArray[i].pin_no, isrArray[i].isr, RISING);
  }
}

void loop(){}

This is great! Thank you for your explanation and example code. I will keep that in mind. :slight_smile:

for( auto& iSR: isrArray)
  {
    attachInterrupt(iSR.pin_no, iSR.isr, RISING);
  }

Let the compiler do the work :wink: