#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h>
// Define the screen width and height for the OLED
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Declare the SSD1306 display object
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Declare the RTC object
RTC_DS3231 rtc;
// Button pins
const int buttonSetHour = 2;
const int buttonSetMinute = 3;
const int buttonSetAlarm = 4;
// Variables to hold current time and alarm time
DateTime now;
int alarmHour = 0;
int alarmMinute = 0;
bool alarmSet = false;
void setup() {
// Initialize the Serial monitor
Serial.begin(9600);
// Initialize the display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C))
{
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.display();
delay(2000);
display.clearDisplay();
// Initialize the RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
// Initialize buttons
pinMode(buttonSetHour, INPUT_PULLUP);
pinMode(buttonSetMinute, INPUT_PULLUP);
pinMode(buttonSetAlarm, INPUT_PULLUP);
}
void loop() {
// Get the current time
now = rtc.now();
// Display the current time
displayCurrentTime();
// Check for button presses to set the alarm
if (digitalRead(buttonSetHour) == LOW) {
alarmHour = (alarmHour + 1) % 24;
delay(200); // Debounce delay
}
if (digitalRead(buttonSetMinute) == LOW) {
alarmMinute = (alarmMinute + 1) % 60;
delay(200); // Debounce delay
}
if (digitalRead(buttonSetAlarm) == LOW) {
alarmSet = !alarmSet;
delay(200); // Debounce delay
}
// Display the alarm time and status
displayAlarmTime();
// Check if the alarm should trigger
if (alarmSet && now.hour() == alarmHour && now.minute() == alarmMinute) {
triggerAlarm();
}
delay(1000); // Update every second
}
void displayCurrentTime() {
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Time: ");
display.print(now.hour());
display.print(":");
display.print(now.minute());
display.print(":");
display.print(now.second());
display.display();
}
void displayAlarmTime() {
display.setCursor(0, 10);
display.print("Alarm: ");
display.print(alarmHour);
display.print(":");
display.print(alarmMinute);
if (alarmSet) {
display.print(" ON");
} else {
display.print(" OFF");
}
display.display();
}
void triggerAlarm() {
// Placeholder function to trigger an alarm
// You can add code here to turn on a buzzer or LED
Serial.println("Alarm triggered!");
}