/*Interrupt tutorial
Use hardware interrupt Pins in Mega: Pin2 =Interrupt Vector 4 Pin3 = Interrupt Vector 5
can have more than one interruptor, but only run one interrupt at a time; don't be rude
create the Interrupt Service Routine (ISR), i.e an interrupt functions. This is created in
the set up function. Then you attach the function the the action (button press)
attachInterruptFUNCTION
attachInterrupt(InterruptVector, ISR, Mode);// or:
attachInterrupt(digitalPinToInterrupt(pin), ISR, Mode);//use a variable instead of
interrupt vector so easy to swap boards and use same code.
InterruptVector- the interrupt number(not the pin)
ISR - name of your ISR function
Mode - how you want to trigger the interrupt
RISING - When and input goes from LOW to HIGH
FALLING - When and input goes from HIGH to LOW
LOW - When the input stays LOW
CHANGE - Whenever the input changes state
*/
int redLED = 12;
int blueLED = 11;
int buttonPin =2;//Pin2 =Interrupt Vector 4
volatile int buttonState; //anytime using an Interrupt Service Routine (ISR) that uses
//a variabe inside, like button state that is constantly changes, you have to use volitile
//this prevents arduino from optimizing it and putting it in storage with all the
//other variables. Instead it puts it in SRAM so it can be updated to the latest value
//from any part of the routine
//DO NOT use delays or millis in interrupts or serial monitor
//functions can be placed at the top (before setup()) or buttom (after void loop())
//This is your ISR function:
void buttonInterrupt () {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
digitalWrite(blueLED, HIGH);
}
if(buttonState ==HIGH){
digitalWrite(blueLED, LOW);
}
}
void setup() {
// put your setup code here, to run once:
pinMode(redLED, OUTPUT);
pinMode(blueLED, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), buttonInterrupt, CHANGE);//can also use vector instead
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(redLED, HIGH);
delay (250);
digitalWrite(redLED, LOW);
delay (250);
}