#include <WiFi.h>
#include "time.h"
#include <Wire.h> // for I2C with RTC module
#include "RTClib.h" //to show time
RTC_DS1307 RTC;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
int hou, minu, sec, wkday, yea = 0;
byte d, wk;
byte mont;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const char* ntpServer = "asia.pool.ntp.org";
const long gmtOffset_sec = 19800;
const int daylightOffset_sec = 3600;
int count = 0;
void printLocalTime()
{
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
while (1);
}
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
hou = timeinfo.tm_hour;
minu = timeinfo.tm_min;
sec = timeinfo.tm_sec;
d = timeinfo.tm_mday;
mont = timeinfo.tm_mon + 1;
yea = timeinfo.tm_year + 1900;
//wkday = timeinfo.tm_mday;
}
void setup()
{
Serial.begin(115200);
//connect to WiFi
Serial.printf("Connecting to %s ", ssid);
wfbegin:
WiFi.begin(ssid, password,6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
//init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
// if (RTC.lostPower())
// {
// Serial.println("RTC power failure, resetting the time!");
// //rtc.adjust(DateTime(F(_DATE), F(TIME_)));
if(count<5)
{
count++;
goto wfbegin;
}
if (! RTC.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
RTC.begin();
// The following lines can be uncommented to set the date and time
RTC.adjust(DateTime(yea, mont, d, hou, minu, sec)); // Set Day-of-Week to SUNDAY
// rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
//rtc.setDate(1, 1, 2014); // Set the date to January 1st, 2014
//rtc.adjust(DateTime(_DATE, __TIME_));
}
void loop()
{
// delay(1000);
// printLocalTime();
DateTime now = RTC.now();
Serial.print(now.day());
Serial.print(".");
Serial.print(now.month());
Serial.print(".");
Serial.print(now.year());
Serial.println();
Serial.print(now.hour() -1);
Serial.print(":");
Serial.print(now.minute());
Serial.print(":");
Serial.print(now.second());
Serial.print(",");
int wk = now.day();
wkday = (wk + 6) % 7;
Serial.print(now.dayOfTheWeek());
int wkk = now.dayOfTheWeek();
Serial.print(daysOfTheWeek[wkk]);
Serial.println();
count = 0;
}