#include <Arduino.h>
// Define pin assignments
const int buttonPin = 2; // Pushbutton connected to pin 2 (INPUT_PULLUP mode)
const int led1Pin = 22; // led1 controlled by digital pin 22 (MSB for overflow)
const int led2Pin = 23; // led2 controlled by digital pin 23 (LSB for overflow)
// Define bargraph pins using the Arduino analog pins A1 - A10
// (note: in Arduino, A1..A10 are available as digital I/O pins)
const int barPins[10] = {A1, A2, A3, A4, A5, A6, A7, A8, A9, A10};
int counter = 0; // counts button presses for the bar graph (0 to 10)
int overflow = 0; // counts how many times counter has overflowed (0 to 3)
unsigned long lastDebounceTime = 0; // to track debounce time
const unsigned long debounceDelay = 150; // debounce duration in milliseconds
void setup() {
// Initialize button pin with internal pullup
pinMode(buttonPin, INPUT_PULLUP);
// Initialize bargraph pins as outputs and turn them off
for (int i = 0; i < 10; i++) {
pinMode(barPins[i], OUTPUT);
digitalWrite(barPins[i], LOW);
}
// Initialize LED pins as outputs and turn them off
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
}
void loop() {
// Read the state of the button (LOW when pressed)
int buttonState = digitalRead(buttonPin);
// Check if button pressed and debounce (only act on a transition)
if (buttonState == LOW) {
// Wait 150 ms to allow bouncing to settle.
if (millis() - lastDebounceTime > debounceDelay) {
// Wait until button is released before acting further.
while(digitalRead(buttonPin) == LOW) {
// Optionally, small delay to avoid busy waiting.
delay(10);
}
// A valid press is detected.
counter++;
if (counter > 10) {
counter = 0;
overflow++;
if (overflow > 3) {
overflow = 0;
}
}
// Update the LED bar graph:
// Light up the first "counter" segments, and turn off the remaining.
for (int i = 0; i < 10; i++) {
if (i < counter) {
digitalWrite(barPins[i], HIGH);
} else {
digitalWrite(barPins[i], LOW);
}
}
// Update overflow LEDs to display the overflow counter in binary.
// We will assign: led1 as the MSB and led2 as the LSB.
// Binary mapping:
// overflow 0: 00 => led1=LOW, led2=LOW
// overflow 1: 01 => led1=LOW, led2=HIGH
// overflow 2: 10 => led1=HIGH, led2=LOW
// overflow 3: 11 => led1=HIGH, led2=HIGH
if (overflow & 0x02) // Check bit1 (MSB)
digitalWrite(led1Pin, HIGH);
else
digitalWrite(led1Pin, LOW);
if (overflow & 0x01) // Check bit0 (LSB)
digitalWrite(led2Pin, HIGH);
else
digitalWrite(led2Pin, LOW);
// Set the last debounce time to the current time after handling a valid press.
lastDebounceTime = millis();
}
}
}