//sketch to test hardware interrupt on NANO: // pin assignments const byte ledPin = 5; //LED on pin D5 with resistor to GROUND - note this must be a pin that supports PWM const byte button = 2; //Button switch is connected between pin 2 and ground. NANO supports "external interrupt" on pins D2, D3 //variables shared between ISR and code must be type volatile. volatile bool toggleVal; volatile bool intFlag = 1; //if ==0 flags that an interrupt has occurred to allow routine to be suspended //For interrupt button debounce: volatile unsigned long lastIntMillis=0; //this is the time of the last interrupt volatile unsigned long debounceMillis = 500; //dont allow another in less than 0.5 sec //variables for flash led routine unsigned long tNow, tLoop=0; boolean ledValue; void setup() { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); //LED off to save power pinMode (button,INPUT_PULLUP); //this is our interrupt button attachInterrupt(digitalPinToInterrupt(button), isr, FALLING); } void loop() { if (toggleVal == LOW) { fadeLed(); } else { flashLed(); } intFlag=1; } void fadeLed(){ // fade in from min to max in increments of 5 points: for (int fadeValue = 30 ; fadeValue <= 250; fadeValue += 10) { if(intFlag == 0)break; //if there's been an interrupt, break out of the loop analogWrite(ledPin, fadeValue); delay(50); //milliseconds } // fade out from max to min in increments of 5 points: for (int fadeValue = 250 ; fadeValue >= 30; fadeValue -= 10) { if(intFlag == 0)break; analogWrite(ledPin, fadeValue); delay(50); } } void flashLed(){ tNow = millis(); if (tNow>=(tLoop+250)){ //if its over 250ms since last change ledValue=!ledValue; digitalWrite(ledPin, ledValue); tLoop=tNow; } } void isr(){ //this is the interrupt service routine //if there has been enough time since the last interrupt then the switch value has been stable, so this isnt a bounce if(millis() - lastIntMillis > debounceMillis){ toggleVal = !toggleVal; intFlag = 0; lastIntMillis = millis(); //record time of interrupt } }