// Pin Definitions
const int interruptPin = 2; // Shared interrupt pin
const int upButton = 3;
const int downButton = 4;
const int selectButton = 5;
const int backButton = 6;
const int ledUp = 10; // LED for "Up"
const int ledDown = 11; // LED for "Down"
const int ledSelect = 12; // LED for "Select"
const int ledBack = 13; // LED for "Back"
// Variables for button states
volatile bool upPressed = false;
volatile bool downPressed = false;
volatile bool selectPressed = false;
volatile bool backPressed = false;
void setup() {
pinMode(interruptPin, INPUT_PULLUP); // Shared interrupt pin with pull-up
pinMode(upButton, INPUT_PULLUP);
pinMode(downButton, INPUT_PULLUP);
pinMode(selectButton, INPUT_PULLUP);
pinMode(backButton, INPUT_PULLUP);
pinMode(ledUp, OUTPUT); // LED pins set as output
pinMode(ledDown, OUTPUT);
pinMode(ledSelect, OUTPUT);
pinMode(ledBack, OUTPUT);
attachInterrupt(digitalPinToInterrupt(interruptPin), handleButtonsISR, CHANGE);
Serial.begin(9600); // Start Serial Monitor
}
void loop() {
// Handle actions based on button flags
if (upPressed) {
handleUp();
upPressed = false; // Reset the flag
}
if (downPressed) {
handleDown();
downPressed = false;
}
if (selectPressed) {
handleSelect();
selectPressed = false;
}
if (backPressed) {
handleBack();
backPressed = false;
}
// Other main loop tasks...
}
void handleButtonsISR() {
// Debounce delay
static unsigned long lastInterruptTime = 0;
unsigned long currentTime = millis();
if (currentTime - lastInterruptTime < 50) return;
lastInterruptTime = currentTime;
// Read button states and set flags
if (!digitalRead(upButton)) {
upPressed = true;
} else if (!digitalRead(downButton)) {
downPressed = true;
} else if (!digitalRead(selectButton)) {
selectPressed = true;
} else if (!digitalRead(backButton)) {
backPressed = true;
}
}
// Function definitions
void handleUp() {
Serial.println("Up Button Pressed");
digitalWrite(ledUp, HIGH); // Turn on the LED
delay(500); // Keep the LED on for a short duration
digitalWrite(ledUp, LOW); // Turn off the LED
}
void handleDown() {
Serial.println("Down Button Pressed");
digitalWrite(ledDown, HIGH); // Turn on the LED
delay(500); // Keep the LED on for a short duration
digitalWrite(ledDown, LOW); // Turn off the LED
}
void handleSelect() {
Serial.println("Select Button Pressed");
digitalWrite(ledSelect, HIGH); // Turn on the LED
delay(500); // Keep the LED on for a short duration
digitalWrite(ledSelect, LOW); // Turn off the LED
}
void handleBack() {
Serial.println("Back Button Pressed");
digitalWrite(ledBack, HIGH); // Turn on the LED
delay(500); // Keep the LED on for a short duration
digitalWrite(ledBack, LOW); // Turn off the LED
}