// Constants for pin assignments
const int buttonPin = 2; // Button connected to digital pin 2
const int segmentPins[] = {3, 4, 5, 6, 7, 8, 9}; // 7-segment display pins
// Digit patterns for 0-9 on a common cathode 7-segment display
const byte digitPatterns[10] = {
B0111111, // 0
B0000110, // 1
B1011011, // 2
B1001111, // 3
B1100110, // 4
B1101101, // 5
B1111101, // 6
B0000111, // 7
B1111111, // 8
B1101111 // 9
};
// Variables
int buttonState = 0; // Variable to hold the button state
int lastButtonState = 0; // Variable to hold the last button state
int counter = 0; // Counter for button presses
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
// Initialize the button pin as an input
pinMode(buttonPin, INPUT);
// Initialize the segment pins as outputs
for (int i = 0; i < 7; i++) {
pinMode(segmentPins[i], OUTPUT);
}
}
void loop() {
// Read the state of the button
int reading = digitalRead(buttonPin);
// Check if the button state has changed
if (reading != lastButtonState) {
// Reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has changed
if (reading != buttonState) {
buttonState = reading;
// Only increment the counter if the new button state is HIGH
if (buttonState == HIGH) {
counter++;
// Reset counter if it goes beyond 9
if (counter > 9) {
counter = 0;
}
// Display the counter on the 7-segment display
displayDigit(counter);
}
}
}
// Save the reading. Next time through the loop, it'll be the lastButtonState
lastButtonState = reading;
}
void displayDigit(int digit) {
// Get the digit pattern
byte pattern = digitPatterns[digit];
// Display the pattern on the 7-segment display
for (int i = 0; i < 7; i++) {
digitalWrite(segmentPins[i], bitRead(pattern, i));
}
}