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.
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.