Klausj
Published © GPL3+

Just another analog clock

With a few lines of code you can have a digital analog clock on a TFT display.

BeginnerFull instructions provided1 hour1,812
Just another analog clock

Things used in this project

Story

Read more

Code

RTC_DS1307.ino

Arduino
Same program but this time using the Adafruit Graphics Library rather than the retired TFT.h included in the Arduino IDE.
/*
  clock
*/
#include "Adafruit_ST7735.h"
#define cs   10
#define dc   9
#define rst  8

Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, rst);

int T = 1000; // can be reduced
int w, h, mx, my, r;
const word c1 = 0xFF00;
const word c2 = 0x0FF0;
const word c3 = 0x00FF;

#include <RTClib.h>
RTC_DS1307 RTC;
DateTime now;

void setup() {
  Serial.begin(115200);
  Serial.println(__FILE__);
  Serial.println(__DATE__ " " __TIME__);
  tft.initR(INITR_BLACKTAB);
  tft.setRotation(3);
  w = tft.width();
  h = tft.height();
  mx = w / 2;
  my = h / 2;
  r = my - 1;
  tft.fillScreen(0);
  tft.drawRect(0, 0, w, h, ST7735_CYAN);
  tft.setCursor(2, 2);
  tft.print("clock");
  byte r2;
  for (int i = 0; i < 60; i++) {
    if (i % 15 == 0)
      r2 = r - 15;
    else if (i % 5 == 0)
      r2 = r - 10;
    else
      r2 = r - 5;
    line(r2, r, i, ST7735_WHITE);
  }
  initRTC();
}

byte second, minute, hour;

void loop() {
  int t = millis() / T;
  // analog:
  // erase previous:
  line(0, r - 15, second, 0);
  line(0, r - 20, minute, 0);
  line(0, r - 25, hour * 5, 0);
  now = RTC.now();
  second = now.second();
  minute = now.minute();
  hour = now.hour();
  // draw new lines:
  line(0, r - 15, second, c1);
  line(0, r - 20, minute, c2);
  line(0, r - 25, hour * 5, c3);
  // digital:
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
  // erase previous:
  tft.fillRect(111, 2, 47, 10, 0);
  tft.setCursor(111, 2);
  print2(hour);
  tft.print(":");
  print2(minute);
  tft.print(":");
  print2(second);
  delay(T);
}

void print2(byte b) {
  if (b < 10) tft.print(0);
  tft.print(b);
}

void line(byte r1, byte r2, float n, word c) {
  float phi = n / 60.0 * TWO_PI - HALF_PI;
  byte x1 = mx + r1 * cos(phi);
  byte y1 = my + r1 * sin(phi);
  byte x2 = mx + r2 * cos(phi);
  byte y2 = my + r2 * sin(phi);
  //tft.stroke(c);
  tft.drawLine(x1, y1, x2, y2, c);
}

void initRTC() {
  RTC.begin();
  Serial.println("shorten pins 2+3 to force"
                 " adjust after upload");
  pinMode(2, OUTPUT);
  pinMode(3, INPUT_PULLUP);
  boolean forceAdjust = !digitalRead(3);
  tft.setCursor(2, h - 20);
  tft.print("RTC is");
  tft.setCursor(2, h - 10);
  if (!RTC.isrunning() || forceAdjust) {
    Serial.println("NOT running!");
    tft.print("RTC adjusted to __TIME__");
    // following line sets the RTC to the
    // date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  else tft.print("running");

}

Credits

Klausj

Klausj

67 projects • 6 followers

Comments