Arduino Mega 2560 pin interrupts

A way to add more pin interrupts to your project, using A8-A15 analog inputs:

 

// mega 2560 pin interrupt

// A8-A15 PK0 - PK7 PCINT16-23

volatile uint8_t portbhistory;
volatile bool intFlag;
volatile int counter=0;
ISR(PCINT2_vect)
{
if (intFlag) return;

cli();

int i;
uint8_t changedbits;

changedbits = PINK ^ portbhistory;
portbhistory = PINK;

if (digitalRead(A8)==0) intFlag = true;
counter++;
sei();

}

void setup()
{

cli();

PCMSK2 = 0b11111111; // Enabling A8 to A15 pins on Mega 2560(PCINT15:8)

DDRK = 0; //   all Pins input
PORTK = 0xff; // turn on pullup for every pin
PCICR |= _BV(PCIE2); // enable interrupt for PCIE2
PCMSK2 = 0xff; // Interrupt at all pins
sei(); // turn on interrupts

Serial.begin(115200);

}

void loop()
{

if (intFlag)
{
delay(100);
Serial.print(counter); Serial.print(" ");
Serial.println(portbhistory);

while (!digitalRead(A8)) {};
intFlag = false;
}

}