#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define BUTTON_PIN 2 // Button connected to digital pin 2
#define DEBOUNCE_DELAY 50 // Debounce delay in milliseconds
LiquidCrystal_I2C lcd(0x27, 16, 2); // 16x2 LCD, address 0x27
volatile int buttonCount = 0;
bool buttonState = HIGH;
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP); // Set button pin as input with internal pull-up
lcd.begin(16, 2); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
Serial.begin(9600); // Start serial communication
lcd.setCursor(0, 0);
lcd.print("Button Counter");
lcd.setCursor(0, 1);
lcd.print("Count: 0");
}
void loop() {
int reading = digitalRead(BUTTON_PIN); // Read the button state
// Debounce the button press
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
// Only increment count if the debounce time has passed
if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
if (reading == LOW && buttonState == HIGH) { // Button was pressed
buttonCount++; // Increment the button count
Serial.print("Count: ");
Serial.println(buttonCount);
lcd.setCursor(7, 1);
lcd.print(" "); // Clear previous count
lcd.setCursor(7, 1);
lcd.print(buttonCount); // Display new count
}
buttonState = reading; // Update the button state
}
lastButtonState = reading; // Store the previous button state for the next loop
}