// Pin definitions
const int upButtonPin = 2; // Pin for counting up
const int downButtonPin = 3; // Pin for counting down
const int ledPins[] = {9, 10, 11}; // Pins for the LEDs (3-bit counter)
int counter = 0; // 3-bit counter value (0 to 7)
const int maxCounter = 7; // Maximum value for 3-bit counter
const int minCounter = 0; // Minimum value for 3-bit counter
unsigned long lastDebounceTimeUp = 0; // Last debounce time for up button
unsigned long lastDebounceTimeDown = 0; // Last debounce time for down button
unsigned long debounceDelay = 500; // Debounce delay time
int lastUpButtonState = HIGH; // Previous up button state
int lastDownButtonState = HIGH; // Previous down button state
void setup() {
// Set the button pins as input pull-up
pinMode(upButtonPin, INPUT);
pinMode(downButtonPin, INPUT);
// Set the LED pins as output
for (int i = 0; i < 3; i++) {
pinMode(ledPins[i], OUTPUT);
}
// Initialize LEDs with the initial counter value
updateLEDs(counter);
}
void loop() {
int upButtonState = digitalRead(upButtonPin); // Read the state of the up button
int downButtonState = digitalRead(downButtonPin); // Read the state of the down button
unsigned long currentTime = millis();
// Debouncing for up button
if (upButtonState == LOW && (currentTime - lastDebounceTimeUp > debounceDelay)) {
if (lastUpButtonState == HIGH) { // Button press detected
if (counter < maxCounter) { // Increment if counter is less than 7
counter++;
}
updateLEDs(counter); // Update the LEDs with the new counter value
lastDebounceTimeUp = currentTime;
}
}
lastUpButtonState = upButtonState;
// Debouncing for down button
if (downButtonState == LOW && (currentTime - lastDebounceTimeDown > debounceDelay)) {
if (lastDownButtonState == HIGH) { // Button press detected
if (counter > minCounter) { // Decrement if counter is greater than 0
counter--;
}
updateLEDs(counter); // Update the LEDs with the new counter value
lastDebounceTimeDown = currentTime;
}
}
lastDownButtonState = downButtonState;
}
// Function to update LEDs based on the counter value
void updateLEDs(int value) {
for (int i = 0; i < 3; i++) {
digitalWrite(ledPins[i], (value >> i) & 1); // Extract each bit and set the corresponding LED
}
}