We can sync the time of a ESP-8266 with a NTP server and then keep time count on the device. It will not need any other additional devices like a DS1307 clock. And once synced with the NTP server it can keep the time even if there is no internet – very handy.
The time formatting and display functions are standard C++ functions.
#include <ESP8266WiFi.h>
#include "TinyDHT.h"
const char *ssid = "xxxxx";
const char *password = "xxxxxx";
#define DHTPIN11 14 // What digital pin we're connected to
#define DHTTYPE11 DHT11 // DHT 11
DHT dht11(DHTPIN11, DHTTYPE11);
struct tm* tm;
float temperature, relHumidity;
String currentTime;
#define countof(a) (sizeof(a) / sizeof(a[0]))
#define LED 13
void setup() {
time_t now = 0;
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
//sync time with the NTP server. First param 19800 seconds = +5:30 for IST, Second Param 0 = DST
configTime(19800, 0, "pool.ntp.org");
//waiting for time to get synced before proceeding. This is not strictly required. Please see after code
do
{
now = time(nullptr);
delay(500);
Serial.print("*");
}while(now < time(nullptr));
pinMode(LED, OUTPUT);
pinMode(DHTPIN11, INPUT);
dht11.begin();
onLedIndicatorChange();
}
void loop() {
// Your code here
time_t now = time(nullptr);
char datestring[30];
strftime(datestring,
countof(datestring),
"%d/%m/%Y %I:%M:%S %p",
localtime(&now)
);
currentTime = datestring;
Serial.println(currentTime);
temperature = dht11.readTemperature();
delay(200);
relHumidity = dht11.readHumidity();
delay(200);
}
void onLedIndicatorChange() {
// Do something
int ledIndicator = 1;
digitalWrite(LED, ledIndicator);
}
configtime listens for connection in the back and will sync as soon as a connection is available. So if a time is not critical for the successive codes or functions then the loop that waits for the sync can be skipped.
configTime(19800, 0, "pool.ntp.org");
do //loop and wait for a sync
{
now = time(nullptr);
delay(500);
Serial.print("*");
}while(now < time(nullptr));