Interrupt doesn't work.

I have problem with the code below this text. When I push the button the index value change, so that works fine.
But problem is when I release the button the index value increases, sometimes 2 times and sometimes 1 time,
which it shouldn't do.

Can someone help me with this issue?

int index = 0;
int switchButton = 2;

void setup()
{
   Serial.begin(9600);
  pinMode(switchButton, INPUT_PULLUP);
  index=0;
  attachInterrupt(digitalPinToInterrupt(switchButton), pin_interupt, CHANGE); 
}

void loop()
{
} 

void pin_interupt() 
{
  delay(1000);
  index++;
     Serial.println("Index:  ");
    Serial.println(index);
  if (index==3){
    index = 0;
    }
 }

Firstly you should never call delay() in an interrupt routine, that can hang the processor
completely. Similarly you should never use Serial calls in an interrupt routine for the same
reason. This is because both operations sometimes wait for progress, but in an interrupt
routine all interrupts are blocked, so no progress can happen.

Secondly you shouldn't be needing interrupts to process a button press. Interrupts are for urgent
responses to hardware on the microsecond timescale, human button presses are on a time scale
of tenth's of a second and should normally be handled in loop().

Thirdly you are not declaring variables used in the interrupt routine as "volatile" - this can mean
things go weirdly wrong - you should always do this.

Fourthly you are not debouncing the button press, which is why you get random numbers of
increments of index.

Perhaps search for "button debounce library" ?

There is no need to use an interrupt to detect a button press unless this is an exercise to learn how to use interrupts.

You should probably set the interrupt for FALLING or RISING rather than change

You should NEVER have print statements inside an interrupt service routine (ISR). Printing needs interrupts to be enabled and they are disabled inside the ISR. Also, printing is very slow and an ISR should complete very quickly.

For the same reasons you should NEVER have delay() inside an ISR.

...R

Try this:

volatile byte index = 0;
byte oldIndex = 0;
const int switchButton = 2;


void setup()
{
  Serial.begin(9600);


  pinMode(switchButton, INPUT_PULLUP);


  attachInterrupt(digitalPinToInterrupt(switchButton), pin_interupt, FALLING);
}


void loop()
{
  byte newIndex = index;


  if (newIndex != oldIndex)
  {
    oldIndex = newIndex;
    Serial.print("Index:  ");
    Serial.println(newIndex);
  }
}


void pin_interupt()
{
  static unsigned long lastInterruptTime = 0;


  if (millis() - lastInterruptTime < 10)
    return;


  lastInterruptTime = millis();
  
  index++;
  if (index == 3)
    index = 0;
}