#if !defined(__AVR_ATmega328P__) #error "This sketch is designed for an Arduino Uno or Duemilenova. You are using a different processor. Check INT0 pin" #endif const byte LED = 13, SW = 2; // must be INT0 pin volatile unsigned char count = 0; unsigned char lastCount = 255; void handleSW() { // ISR digitalWrite(LED, digitalRead(SW)); count++; } void handleOtherStuff() { if (count != lastCount) { Serial.print("Count "); Serial.println(count); lastCount = count; } } void setup() { //Start up the serial port Serial.begin(9600); while (!Serial); // for Leonardo Serial.println(F("Initialized example4")); // configure the pins pinMode(LED, OUTPUT); pinMode (SW, INPUT_PULLUP); // Attach the ISR attachInterrupt(INT0, handleSW, CHANGE); } void loop() { handleOtherStuff(); }
In example 3, our mainline code did not know anything about the switch closure. In this sketch, we look at how to communicate between an ISR and mainline code. The ISR now, in addition to toggling the LED, increments a variable named count
. Our handleOtherStuff() routine now looks to see if count
has changed and if it has, it prints a message to the serial port. You will notice that count
is declared as volatile
. This tells the compiler that the variable may change at any time. So, instead of saving the value in a register, the compiler fetches the value from memory each time it is accessed. The interrupt is specified as CHANGE, which means any time the signal at pin 2 changes, assert the interrupt. Other possible values are RISING, FALLING, HIGH, and LOW.