Interrupt not working all the time

Im just trying to test the interrupt function. It should change and print new state( 0 or 1) every time I connect or disconnect pin to my breadboard, but 60%- 70% times it doesn't change the state, why? Thanks, sorry Im just new to this

volatile byte state = false;
int switchstate = 2;
 
void setup() {
pinMode(switchstate, INPUT_PULLUP);
attachInterrupt(0, isr, CHANGE);
Serial.begin (9600);
state = digitalRead(switchstate);
}

void loop() {
  Serial.println(state);
 }

void isr(){
  state = !state;
}

Looks to me like your code tries to print on every iteration of loop(). Serial may not be able to keep up. Try printing only when 'state' changes from its previous value.

It may help to know the circuitry behind this setup. Post a wiring diagram.

it works if I put state = digitalRead(switchstate) in loop.

pinMode(switchstate, INPUT_PULLUP);

It is far more common to use pin in the name of variables that hold pin numbers.

kashi786:
it works if I put state = digitalRead(switchstate) in loop.

Is that in a program that also has the ISR?

Which is why you should always post a complete program!

If you are using digitalRead() in loop() and also setting the variable state with an ISR goodness knows what is really happening. Do one or the other - not both.

I suggest you don't print to the serial monitor more than 5 times per second.

...R

Robin2:
I suggest you don't print to the serial monitor more than 5 times per second.

Or, as already suggested, only when the variable changes. There is no value added by printing it every time through loop() when it hasn't changed.