#include "functions.h"
#include "TM1637Display.h"
#include "DS130X.h"
#ifdef ESP8266
#include <ESP8266WiFi.h>
#else
#include <WiFi.h>
#endif
#include <time.h>
#define clkPin 12
#define DIO 14
#define ssid "Wokwi-GUEST"
#define password ""
#define NTP_SERVER "ch.pool.ntp.org"
#define TZ_INFO "IST-5:30"
tm timeinfo;
time_t now;
TM1637Display display(clkPin, DIO);
DS1307 rtc;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
rtcPrintDateTime();
Serial.println("\n\nNTP Time Test\n");
WiFi.begin(ssid, password);
int counter = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(200);
if (++counter > 100) ESP.restart();
Serial.print ( "." );
}
Serial.println("\n\nWiFi connected\n\n");
// Setting Timezone Info
configTime(0, 0, NTP_SERVER);
setenv("TZ", TZ_INFO, 1);
if(getNTPtime(10)){
printCurrentTime();
rtc.setTime(timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
rtc.setDate(timeinfo.tm_mday, timeinfo.tm_mon + 1, timeinfo.tm_year - 100, timeinfo.tm_wday + 1);
}else{
Serial.println("Unable to get Time from Server!");
}
display.setBrightness(0x0f);
display.showNumberDecEx(timeinfo.tm_min * 100 + timeinfo.tm_sec, 0b01000000, true);
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
uint8_t sec, min;
min = rtc.read(1);
sec = rtc.read(0);
display.showNumberDecEx(min*100 + sec, sec%2 ? 0b01000000 : 0, true);
delay(100);
}
bool getNTPtime(int sec) {
{
uint32_t start = millis();
do {
time(&now);
localtime_r(&now, &timeinfo);
Serial.print(".");
delay(10);
} while (((millis() - start) <= (1000 * sec)) && (timeinfo.tm_year < (2023 - 1900)));
if (timeinfo.tm_year < (2023 - 1900)) return false; // the NTP call was not successful
printCurrentTime();
}
return true;
}
void printCurrentTime(){
char time_output[30];
strftime(time_output, 30, "%a %d-%m-%y %T", localtime(&now));
Serial.println(time_output);
Serial.println();
}
void rtcPrintDateTime(){
String dow = rtc.dowAbbr(); // Day of week (abbreviated)
String date = rtc.dateStr(); // Read date
String time = rtc.timeStr(); // Read time
// Print the data in format:
// dow, date time
Serial.println(dow + ", " + date + " " + time);
}