WeMOS: D1 R1 mini RTC NTP Set

From OnnoWiki
Jump to navigation Jump to search

Library

https://github.com/Naguissa/uRTCLib

Code

#include <Wire.h>
// #include "RTClib.h"
#include "uRTCLib.h"
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

// RTC_DS1307 rtc;

// uRTCLib rtc;
uRTCLib rtc(0x68);

const char *ssid     = "o1";
const char *password = "Dzaq1993!";
 
const long utcOffsetInSeconds = 25200;  // GMT+7 Jakarta 
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds); 

void setup () {
  Serial.begin(9600);
  URTCLIB_WIRE.begin(); 

  WiFi.begin(ssid, password); 
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  timeClient.begin();
  timeClient.update(); 

  // Following line sets the RTC with an explicit date & time
  // for example to set April 3 13 2023 at 12:56 you would call:
  // rtc.set(0, 56, 12, 5, 3, 4, 23);
  // rtc.set(second, minute, hour, dayOfWeek, dayOfMonth, month, year)
  // set day of week (1=Sunday, 7=Saturday) 

  rtc.set(timeClient.getSeconds(), timeClient.getMinutes(), timeClient.getHours(), timeClient.getDay(), 3, 4, 23);

  // update RTC dari clock komputer
  // if (! rtc.isrunning()) {
  //   Serial.println("RTC is NOT running!");
  //  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));//update rtc dari waktu komputer
  // }
}

void loop() {
  rtc.refresh();  

  Serial.print(daysOfTheWeek[rtc.dayOfWeek()]);
  Serial.print(" , ");
  Serial.print(rtc.day());
  Serial.print(' ');
  Serial.print(rtc.month());
  // Serial.print(cMonth[rtc.month()-1]);
  Serial.print(' ');
  Serial.print(2000+rtc.year()); 

  print2digits(rtc.hour());
  Serial.print(':');
  print2digits(rtc.minute());
  Serial.print(':');
  print2digits(rtc.second());
  Serial.print('\n');
    
  delay(1000);
}

void print2digits(int number) {
  if (number >= 0 && number < 10) {
    Serial.write('0');
  }
  Serial.print(number);
}