#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "RTClib.h"
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
#define button1 2 // SET
#define button2 3 // MODE
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
RTC_DS1307 rtc;
unsigned long timing1 = 0; // 0.5 sec flashing
unsigned long timing2 = 0; // button debounce
boolean dd = 1; // ":"
int mode = 0; // 0 -> Display clock, 1 -> Hours, 2 -> Minutes
boolean f_button1, f_button2 = 0;
boolean set_h, set_m = 0;
int h, m;
void setup() {
Serial.begin(9600);
rtc.begin();
display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
display.setTextSize(4);
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
}
void loop() {
if (millis() - timing1 >= 500) {
timing1 = millis();
if (mode == 0) {
DateTime now = rtc.now();
h = now.hour(), DEC;
m = now.minute(), DEC;
}
oledDisplayTime();
dd = !dd;
}
// MODE
if (digitalRead(button2) == LOW && f_button2 == 0 && millis() - timing2 > 100) {
f_button2 = 1;
timing1 = millis();
if (mode == 1 || mode == 2) {
rtc.adjust(DateTime(2023, 10, 24, h, m, 0));
}
mode = mode + 1;
if (mode > 2) {
mode = 0;
}
}
if (digitalRead(button2) == HIGH && f_button2 == 1) {
f_button2 = 0;
}
// SET
if (digitalRead(button1) == LOW && f_button1 == 0 && millis() - timing2 > 100) {
f_button1 = 1;
timing1 = millis();
dd = 1;
// Hour
if (mode == 1) {
h = h + 1;
if (h > 23) {
h = 0;
}
}
// Minute
if (mode == 2) {
m = m + 1;
if (m > 59) {
m = 0;
}
}
oledDisplayTime();
}
if (digitalRead(button1) == HIGH && f_button1 == 1) {
f_button1 = 0;
}
}
void oledDisplayCenter() {
String data = String(h) + ":" + String(m);
int16_t x1;
int16_t y1;
uint16_t width;
uint16_t height;
display.getTextBounds(data, 0, 0, &x1, &y1, &width, &height);
display.setCursor((SCREEN_WIDTH - width) / 2, (SCREEN_HEIGHT - height) / 2);
}
void oledDisplayTime() {
display.clearDisplay();
oledDisplayCenter();
switch (mode) {
case 0:
display.setTextColor(SSD1306_WHITE);
display.print(h);
if (!dd) {
display.setTextColor(SSD1306_BLACK);
}
display.print(":");
display.setTextColor(SSD1306_WHITE);
display.print(m);
break;
case 1:
display.setTextColor(SSD1306_WHITE);
if (!dd) {
display.setTextColor(SSD1306_BLACK);
}
display.print(h);
display.setTextColor(SSD1306_WHITE);
display.print(":");
display.print(m);
break;
case 2:
display.setTextColor(SSD1306_WHITE);
display.print(h);
display.print(":");
if (!dd) {
display.setTextColor(SSD1306_BLACK);
}
display.print(m);
break;
}
display.display();
}