// Setup libraries and variables
#include <U8glib.h>
#include <RTClib.h>
U8GLIB_SSD1306_128X64 u8g;
RTC_DS1307 rtc;
void setup() {
// Setup serial and check for rtc
u8g.setFont(u8g_font_7x13);
Serial.begin(115200);
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
abort();
}
}
void loop() {
// Get current time and use it as input
// to analogClock and digitalClock function
DateTime now = rtc.now();
u8g.firstPage();
do {
u8g.setColorIndex(1);
u8g.drawCircle(30,30,21);
// Show hour mark for every hour
for(int i =0; i<12; i++){
mark(i);
}
analogClock(now.second(), now.minute(), now.hour());
digitalClock(now.second(), now.minute(), now.hour());
} while ( u8g.nextPage() );
}
// Show hour marks on analog clock
void mark(int h){
float x1, y1, x2, y2;
float center = 30;
float convertToDeg = 0.0175; // 3.141 / 180
h=h*30;
h=h+270;
x1=16*cos(h*convertToDeg);
y1=16*sin(h*convertToDeg);
x2=21*cos(h*convertToDeg);
y2=21*sin(h*convertToDeg);
u8g.drawLine(center+x1, center+y1, center+x2, center+y2);
}
// Show second hand on analog clock
void drawSec(int secs){
int x1, y1;
float center = 30;
float convertToDeg = 0.0175; // 3.141 / 180
secs=(secs*6) + 270;
x1=18*cos(secs * convertToDeg);
y1=18*sin(secs * convertToDeg);
u8g.drawLine(center, center, center+x1, center+y1);
}
// Show minute hand on analog clock
void drawMin(int mins){
int x1, y1;
float center = 30;
float convertToDeg = 0.0175; // 3.141 / 180
mins=(mins * 6) + 270;
x1=18*cos(mins * convertToDeg);
y1=18*sin(mins * convertToDeg);
u8g.drawLine(center, center, center+x1, center+y1);
}
// Show hour hand on analog clock
void drawHour(int hours, int mins){
float x1, y1;
float center = 30;
float convertToDeg = 0.0175; // 3.141 / 180
hours=((hours*30)+(mins/2)) + 270;
x1=10*cos(hours * convertToDeg);
y1=10*sin(hours * convertToDeg);
u8g.drawLine(center, center, center+x1, center+y1);
}
// Show current time in digital clock format
void digitalClock(int sec, int minute, int hour){
char time[10];
String hours = String(hour);
String mins = String(minute);
String secs = String(sec);
if(hour<10) hours = "0" + hours;
if(minute<10) mins = "0" + mins;
if(sec<10) secs = "0" + secs;
strcpy(time, hours.c_str());
strcat(time, ":");
strcat(time, mins.c_str());
strcat(time, ":");
strcat(time, secs.c_str());
u8g.drawStr(60, 30, time);
}
// Putting drawSec, drawMin and drawHour
// together to show analog clock
void analogClock(int sec, int minute, int hour){
drawSec(sec);
drawMin(minute);
drawHour(hour, minute);
}