#include <Wire.h>
#include <RTClib.h> // RTC library
#include <LiquidCrystal_I2C.h> // LCD library
// Pin Definitions
const int buttonPin = PA0; // Button connected to PA0
const int ledPin = PC13; // LED connected to PC13
const int buzzerPin = PB0; // Buzzer connected to PB0
// LCD and RTC setup
LiquidCrystal_I2C lcd(0x3F, 16, 2); // LCD with I2C address 0x3F
RTC_DS3231 rtc; // DS3231 RTC module
int pressCount = 0;
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("Starting setup...");
// Initialize the button
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Initialize LCD
lcd.begin(16, 2); // 16x2 LCD
lcd.backlight();
lcd.print("Press Button!");
// Initialize I2C
Wire.begin(PB7, PB6); // PB7 = SDA, PB6 = SCL
Serial.println("I2C Initialized.");
// Initialize RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
lcd.clear();
lcd.print("RTC Error");
while (1); // Halt program if RTC is not found
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting time...");
rtc.adjust(DateTime(2025, 4, 28, 12, 0, 0)); // Set to a specific time
}
Serial.println("Setup complete.");
}
void loop() {
// Check if the button is pressed
if (digitalRead(buttonPin) == LOW) { // Button is pressed (active-low)
pressCount++;
// Turn on the LED and Buzzer for feedback
digitalWrite(ledPin, HIGH);
digitalWrite(buzzerPin, HIGH);
// Get the current time from RTC
DateTime now = rtc.now();
// Log the event
Serial.print("Button Pressed: Event #");
Serial.print(pressCount);
Serial.print(" | Time: ");
Serial.print(now.hour());
Serial.print(":");
Serial.print(now.minute());
Serial.print(":");
Serial.print(now.second());
Serial.print(" ");
Serial.print(now.day());
Serial.print("/");
Serial.print(now.month());
Serial.print("/");
Serial.println(now.year());
// Update LCD display
lcd.clear();
lcd.print("Event: " + String(pressCount));
lcd.setCursor(0, 1);
lcd.print("Time: ");
lcd.print(now.hour());
lcd.print(":");
lcd.print(now.minute());
lcd.print(":");
lcd.print(now.second());
// Wait for the button to be released
while (digitalRead(buttonPin) == LOW) {
delay(10); // Small delay to avoid multiple counts
}
// Turn off the LED and Buzzer after the event
digitalWrite(ledPin, LOW);
digitalWrite(buzzerPin, LOW);
}
delay(100); // Small delay to avoid debounce
}