Simplifying AttachInterrupt Code with 21 sensors

So I have 21 reed switches that I need to know when they are LOW to detect when a panel has been hit. I declared the pin # using an array. All of the switches need to be attached to an interrupt so I went through one by one and declared each attachInterrupt and created a corresponding function to that attachInterrrupt.

const int reedpins[] = {22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42}

pinMode(reedpins[1], INPUT_PULLUP);

attachInterrupt(digitalPinToInterrupt(reedpins[1]), sensor1, FALLING);

void sensor1(){

The Serial.write(63) is just a number used to state incoming data from the arduino to the other arduino using Xbee communication.

My question is, if there is a way I can simplify this instead of copying and pasting the function 20 more times? Possibly using one function for all 21 sensors.

The switches are supposed to send their pin # so I know which switch was tripped and the receiving arduino will light an LED to display which switch was tripped. I thought about using the function to run through each sensor using a for loop and find which one is low but I only have a short amount of time for the pin is HIGH again (about 250ms), so I' am not sure if that will work effectively.

Is this on a Mega? You don't have that many external interrupts. You'll have to use pin change interrupts so all the pins that share a common port will have to share a common ISR and the ISR will have to test the port to see which pin changed.

On the Mega, the external interrupts (the ones that use attachInterrupt) work on pins 2,3,18,19,20 and 21.

You could use Direct Port Manipulation, put all the switches on 3 ports, and Poll them every 100mS or so; then act when you get a result that is Not 0xFF for one of the bytes.

I would certainly try @CrossRoad's suggestion. But you have not told us what you are trying to acheive and a FOR loop with digitalRead() may be sufficient, and a great deal simpler.

The line Serial.write(reedpins[1]); just prints the number of the pin. You need digitalRead(reedpins[1]); to get the current status.


So I am using and Arduino Due which allows me to use all digital pins on attachinterrupts.

@Robin2 basically I have 21 pins all reading HIGH at steady state. When one of the panels is tripped it will go low for a second but then come back to HIGH quickly. The reason I went with interrupts is because it would tell me exactly when I panel is tripped and the reason I did Serial.write(reedpin[1]) was to have it send which pin has been tripped to the other arduino. Thanks for the input though.