#include <U8glib.h>
#include <RTClib.h>
#include <math.h>
RTC_DS1307 rtc;
U8GLIB_SSD1306_128X64 u8g;
#define WIDTH 128
#define HEIGHT 64
enum clock_modes {
DIGITAL,
ANALOG,
STOPWATCH,
};
int mode = DIGITAL; //default mode
int temp_mode; //used to restore previous mode
const int button = 3;
void draw_digital()
{
String hour = String(rtc.now().hour());
String minute = String(rtc.now().minute());
String time = String(hour + " : " + minute);
u8g.setPrintPos(33, 38);
u8g.print(time.c_str());
}
void draw_analog()
{
DateTime now = rtc.now();
double hours = now.hour();
double minutes = now.minute();
double minute_angle = minutes * (M_PI / 30) - (M_PI / 2);
u8g.drawLine(64, 32, 30 * cos(minute_angle) + 64, 30 * sin(minute_angle) + 32);
double hour_angle = ((hours + (minutes / 60)) * M_PI / 6) - (M_PI / 2);
u8g.drawLine(64, 32, 15 * cos(hour_angle) + 64, 15 * sin(hour_angle) + 32);
}
int start_time; //time the stopwatch was started
void draw_stopwatch()
{
String time = String(millis() - start_time);
u8g.setPrintPos(33, 38);
u8g.print(time.c_str());
}
void read_option()
{
String s = Serial.readStringUntil('\n');
switch (s.charAt(0)) {
case 'A':
mode = ANALOG;
break;
case 'D':
mode = DIGITAL;
break;
default:
Serial.println("unrecognised input");
}
}
void button_ISR()
{
if (mode != STOPWATCH) {
temp_mode = mode;
start_time = millis();
mode = STOPWATCH;
} else {
mode = temp_mode;
}
}
void setup()
{
u8g.setFont(u8g_font_tpssb);
u8g.setColorIndex(1);
Serial.begin(9600);
pinMode(button, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(button), button_ISR, FALLING);
rtc.begin();
Serial.println("Enter 'A' for analog or 'D' for digital modes.");
}
void loop() {
//picture loop
u8g.firstPage();
do {
if (Serial.available() > 0) {
read_option();
}
switch (mode) {
case DIGITAL:
draw_digital();
break;
case ANALOG:
draw_analog();
break;
case STOPWATCH:
draw_stopwatch();
}
} while (u8g.nextPage());
}