const int buttonPin1 = 2; // Green button pin
const int buttonPin2 = 3; // Red button pin
const int greenLEDPin = 12; // Green LED pin
const int redLEDPin = 13; // Red LED pin
volatile bool greenLEDState = true; // State of the green LED
volatile bool redLEDState = true; // State of the red LED
void setup()
{
Serial.begin(9600);
pinMode(buttonPin1, INPUT_PULLUP); // Set green button as input with pull-up resistor
pinMode(buttonPin2, INPUT_PULLUP); // Set red button as input with pull-up resistor
pinMode(greenLEDPin, OUTPUT); // Set green LED pin as output
pinMode(redLEDPin, OUTPUT); // Set red LED pin as output
digitalWrite(greenLEDPin, HIGH); // To constantly keep green LED on
digitalWrite(redLEDPin, HIGH); // To constantly keep red LED on
Serial.println("Press any button to see effect");
// Attach interrupts for both buttons
attachInterrupt(digitalPinToInterrupt(buttonPin1), handleGreenButton, CHANGE); // Trigger on any change
attachInterrupt(digitalPinToInterrupt(buttonPin2), handleRedButton, CHANGE); // Trigger on any change
}
void loop()
{
}
void handleGreenButton()
{
if (digitalRead(buttonPin1) == LOW) { // Falling edge detected (button pressed)
Serial.println("Green Button Pressed!");
digitalWrite(greenLEDPin, LOW); // Turn off the green LED
greenLEDState = false; // To update the state
} else { // Rising edge detected (button released)
Serial.println("Green Button Released!");
digitalWrite(greenLEDPin, HIGH); // Turn on the green LED
greenLEDState = true; // To update the state
}
}
void handleRedButton()
{
if (digitalRead(buttonPin2) == LOW) { // Falling edge detected (button pressed)
Serial.println("Red Button Pressed!");
digitalWrite(redLEDPin, LOW); // Turn off the red LED
redLEDState = false; // To update the state
} else { // Rising edge detected (button released)
Serial.println("Red Button Released!");
digitalWrite(redLEDPin, HIGH); // Turn on the red LED
redLEDState = true; // To update the state
}
}