digital clock
#include <Arduino.h>
#include <Wire.h>
#include "RTClib.h"
#include <TM1637Display.h>
#define CLK 2 // TM1637 PIN to Arduino
#define DIO 3
RTC_DS3231 RTC;
TM1637Display display(CLK, DIO);
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int Button1=8; // Button SET
int Button2=7; // Button for +
int Button3=6; // Button for -
int hrs;
int mins;
int states =0;
unsigned long previousSecond = 0;
const long interval = 2;
uint8_t data[] = { 0x00, 0x00, 0x00, 0x00 };
const uint8_t SEG_DASH[] = {
SEG_G,
SEG_G,
SEG_G,
SEG_G
};
void setup()
{
pinMode(Button1,INPUT_PULLUP);
pinMode(Button2,INPUT_PULLUP);
pinMode(Button3,INPUT_PULLUP);
int states=0;
#ifndef ESP8266
while (!Serial); // for Leonardo/Micro/Zero
#endif
// Serial.begin(9600);
if (! RTC.begin()) {
// Serial.println("Couldn't find RTC");
while (1);
}
if (RTC.lostPower()) {
Serial.println("RTC lost power, lets set the time!");
//rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop()
{
display.setBrightness(0x0f);
if(digitalRead(Button1)==LOW){
delay(20);
if(digitalRead(Button1)==LOW){
states=states+1;
delay(100);
}
}
if (states==0)
{
DisplayCurrentTime(); // Show Current time
}
if (states==1)
{
SetHour();
}
if (states==2)
{
SetMinute();
}
if (states==3)
{
SetTime();
states=0;
}
}
void DisplayCurrentTime ()
{
DateTime now = RTC.now();
uint8_t hour12 = now.hour()%12 == 0? 12 : now.hour()%12;
String st = String(hour12,DEC);
char dateBuffer[12];
sprintf(dateBuffer,"%02u%02u",hour12,now.minute());
String myTime=String(dateBuffer);
int myTimeInt=myTime.toInt();
display.showNumberDec(myTimeInt,false,4,0);
unsigned long currentSecond = now.second();
if (currentSecond - previousSecond >= interval)
{
previousSecond = currentSecond;
display.showNumberDecEx(myTimeInt, (0x80 >> 1),false,4,0);
delay(1000);
}
hrs=now.hour();
mins=now.minute();
}
void SetHour()
{
display.setSegments(data);
if(digitalRead(Button2)==LOW)
{
if(hrs==23)
{
hrs=0;
}
else
{
hrs=hrs+1;
delay(100);
}
}
if(digitalRead(Button3)==LOW)
{
if(hrs==0)
{
hrs=23;
}
else
{
hrs=hrs-1;
delay(100);
}
}
display.showNumberDec(hrs, false, 2, 2);
}
void SetMinute()
{
display.setSegments(data);
if(digitalRead(Button2)==LOW)
{
if (mins==59)
{
mins=0;
}
else
{
mins=mins+1;
delay(100);
}
}
if(digitalRead(Button3)==LOW)
{
if (mins==0)
{
mins=59;
}
else
{
mins=mins-1;
delay(100);
}
}
display.showNumberDec(mins, false, 2, 2);
}
void SetTime()
{
display.setSegments(SEG_DASH);
RTC.adjust(DateTime(2022,1,1,hrs,mins,0));
delay(1000);
}