#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include <math.h>

#define TFT_DC 35
#define TFT_CS 3
#define TFT_MOSI 37
#define TFT_CLK 36

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK);

const int centerX = 120;  // Center of the clock
const int centerY = 160;
const int radius = 100;   // Radius of the clock

unsigned long previousMillis = 0;
int hours = 10;
int minutes = 58;
int seconds = 50;

void setup() {
  Serial.begin(115200);
  tft.begin();

  // Configure the direction of the display
  const uint8_t mode = 0xc8;
  tft.sendCommand(ILI9341_MADCTL, &mode, 1);

  tft.fillScreen(ILI9341_BLACK);
  drawClockFace();  // Draw the clock face
  drawHand(hours % 12, minutes, seconds, ILI9341_WHITE);  // Draw initial hands
}

void loop() {
  unsigned long currentMillis = millis();

  // Update the time every second
  if (currentMillis - previousMillis >= 1000) {
    previousMillis = currentMillis;

    // Erase the old hands
    drawHand(hours % 12, minutes, seconds, ILI9341_BLACK);

    // Increment time
    seconds++;
    if (seconds >= 60) {
      seconds = 0;
      minutes++;
      if (minutes >= 60) {
        minutes = 0;
        hours++;
        if (hours >= 24) {
          hours = 0;
        }
      }
    }

    // Draw the new hands
    drawHand(hours % 12, minutes, seconds, ILI9341_WHITE);
  }
}

void drawClockFace() {
  // Draw the clock outline
  tft.drawCircle(centerX, centerY, radius, ILI9341_WHITE);

  // Draw hour marks
  for (int i = 0; i < 12; i++) {
    float angle = i * 30 * PI / 180;
    int xStart = centerX + cos(angle) * (radius - 10);
    int yStart = centerY + sin(angle) * (radius - 10);
    int xEnd = centerX + cos(angle) * radius;
    int yEnd = centerY + sin(angle) * radius;
    tft.drawLine(xStart, yStart, xEnd, yEnd, ILI9341_WHITE);
  }
}

void drawHand(int hours, int minutes, int seconds, uint16_t color) {
  // Calculate and draw the hour hand
  float hourAngle = ((hours % 12) + minutes / 60.0) * 30 * PI / 180;
  int hourX = centerX + cos(hourAngle) * (radius - 50);
  int hourY = centerY + sin(hourAngle) * (radius - 50);
  tft.drawLine(centerX, centerY, hourX, hourY, color);

  // Calculate and draw the minute hand
  float minuteAngle = (minutes + seconds / 60.0) * 6 * PI / 180;
  int minuteX = centerX + cos(minuteAngle) * (radius - 30);
  int minuteY = centerY + sin(minuteAngle) * (radius - 30);
  tft.drawLine(centerX, centerY, minuteX, minuteY, color);

  // Calculate and draw the second hand
  float secondAngle = seconds * 6 * PI / 180;
  int secondX = centerX + cos(secondAngle) * (radius - 20);
  int secondY = centerY + sin(secondAngle) * (radius - 20);
  tft.drawLine(centerX, centerY, secondX, secondY, color);
}
Loading
m5stack-core-s3