#include <Wire.h>
#include <RTClib.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <math.h>
RTC_DS1307 rtc;
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
Serial.begin(9600);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (!rtc.isrunning()) {
Serial.println("RTC is not running");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
}
void loop() {
DateTime now = rtc.now();
display.clearDisplay();
drawClock(now.hour(), now.minute(), now.second());
display.display();
}
void drawClock(int hour, int minute, int second) {
int16_t x0 = SCREEN_WIDTH / 2;
int16_t y0 = SCREEN_HEIGHT / 2;
int16_t radius = SCREEN_WIDTH / 4;
// Draw clock face
display.drawCircle(x0, y0, radius, SSD1306_WHITE);
display.fillCircle(x0, y0, 2, SSD1306_WHITE);
// Draw hour lines and numbers
for (int i = 0; i < 12; i++) {
float angle = PI / 6 * i - PI / 2; // Offset by -90 degrees to start at the top
int16_t x1 = x0 + cos(angle) * (radius * 0.8);
int16_t y1 = y0 + sin(angle) * (radius * 0.8);
int16_t x2 = x0 + cos(angle) * (radius * 0.75); // Move the numbers slightly towards the center
int16_t y2 = y0 + sin(angle) * (radius * 0.75);
display.drawLine(x1, y1, x2, y2, SSD1306_WHITE);
// Print hour number
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(x2 - 3, y2 - 3); // Adjust position of the numbers
if (i == 0) {
display.setTextSize(1); // Set the size to normal
display.setCursor(x2 - 4, y2 - 2); // Move the 12 to the top and adjust position
display.print(12);
} else {
display.print(i);
}
}
// Draw hour hand
float angle_hour = PI / 6 * hour + PI / 6 * (minute / 60.0); // Adjust angle calculation
drawHand(x0, y0, radius * 0.5, angle_hour, SSD1306_WHITE);
// Draw minute hand
float angle_minute = PI / 30 * minute + PI / 30 * (second / 60.0); // Adjust angle calculation
drawHand(x0, y0, radius * 0.8, angle_minute, SSD1306_WHITE);
// Draw second hand
float angle_second = PI / 30 * second;
drawHand(x0, y0, radius * 0.9, angle_second, SSD1306_WHITE);
}
void drawHand(int16_t x0, int16_t y0, int16_t length, float angle, uint16_t color) {
int16_t x_end = x0 + cos(angle - PI / 2) * length;
int16_t y_end = y0 + sin(angle - PI / 2) * length;
display.drawLine(x0, y0, x_end, y_end, color);
}
Loading
ssd1306
ssd1306