WeMOS: D1 R1 mini LCD DS1307 I2C RTC NTP update daily

From OnnoWiki
Jump to navigation Jump to search

Code

#include "Arduino.h"
#include "uRTCLib.h"
// uRTCLib rtc;
uRTCLib rtc(0x68);
/*
 I2C LCD  ESP8266-Wenos D1 Mini
 GND          GND
 VCC          VIN
 SDA          D2
 SCL          D1
*/
#include <LiquidCrystal_I2C.h>
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

// set the LCD number of columns and rows
int lcdColumns = 16;
int lcdRows = 2;

LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); 

const char *ssid     = "o1";
const char *password = "Dzaq1993!";
const long utcOffsetInSeconds = 25200;  // GMT+7 Jakarta 

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

char cMonth[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
char DoW[7][10] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

void setup() {
  // Serial.begin(9600);
  // delay(3000); // wait for console opening
  
  lcd.begin( 5, 4 );// initialize LCD
  lcd.init();
  // turn on LCD backlight                      
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(0,0); 

  URTCLIB_WIRE.begin();
  WiFi.begin(ssid, password); 
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    lcd.print ( "." );
  }
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print ( "WiFi connected" );
  delay( 3000 );
  lcd.clear();
    
  timeClient.begin();
}

void loop() {
  rtc.refresh(); 
  if( rtc.hour()==1 && rtc.minute()==0 ) {
    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(), rtc.day(), rtc.month(), rtc.year());
    delay(59000);
  }

  lcd.setCursor(0,0);
  lcd.print( DoW[rtc.dayOfWeek()] );
  lcd.print(", ");
  lcd.print(rtc.day());
  lcd.print(' ');
  // lcd.print(rtc.month());
  lcd.print(cMonth[rtc.month()-1]);
  lcd.print(' ');
  lcd.print(2000+rtc.year()); 

  lcd.setCursor(4,1);
  print2digits(rtc.hour());
  lcd.print(':');
  print2digits(rtc.minute());
  lcd.print(':');
  print2digits(rtc.second());
    
  delay(1000);
}

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