const unsigned long LED1_DELAY = 3000; // Delay for LED 1
const unsigned long LED2_DELAY = 3000; // Delay for LED 2
unsigned long previousMillis1 = 0; //store the previous time when the LEDs were turned on
unsigned long previousMillis2 = 0; //store the previous time when the LEDs were turned on
bool led1State = LOW; //store the state of LED 1 and LED 2
bool led2State = LOW;
const int led1Pin = 12; // store the pins that the LEDs and buttons are connected to
const int led2Pin = 13;
const int button1Pin = 3;
const int button2Pin = 2;
volatile int button1Pressed = LOW; //variables that store whether button 1 and button 2 are pressed
volatile int button2Pressed = LOW;
void setup() {
Serial.begin(9600);
pinMode(led1Pin, OUTPUT); //set as OUTPUT
pinMode(led2Pin, OUTPUT); //set as OUTPUT
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
// Attach interrupts to buttons
attachInterrupt(digitalPinToInterrupt(button1Pin), button1ISR, FALLING); //interrupt on LED 1
attachInterrupt(digitalPinToInterrupt(button2Pin), button2ISR, FALLING); //interrupt on LED 2
}
void loop() {
unsigned long currentMillis = millis();
// if the buttonPressed variable is true it will turn on the corresponding LED
if (button1Pressed) {
if (!led1State && (currentMillis - previousMillis1) > LED1_DELAY) { //enough time has elapsed since the last state change for LED 1
led1State = true;
digitalWrite(led1Pin, HIGH);
previousMillis1 = currentMillis;
}
//when releasing the button, the buttonPressed variable is set back to false
button1Pressed = LOW;
} else {
led1State = false;
digitalWrite(led1Pin, LOW);
}
if (button2Pressed) {
if (!led2State && (currentMillis - previousMillis2) > LED2_DELAY) { //enough time has elapsed since the last state change for LED 2
led2State = true;
digitalWrite(led2Pin, HIGH);
previousMillis2 = currentMillis;
}
//when releasing the button, the buttonPressed variable is set back to false
button2Pressed = LOW;
} else {
led2State = LOW;
digitalWrite(led2Pin, LOW);
}
}
void button1ISR() {
button1Pressed = true;
}
void button2ISR() {
button2Pressed = true;
}