book collections email follower instructable user
Picture of NODEMCU Lua ESP8266 With Real Time Clock (RTC) & EEPROM

Getting the correct time is essential if you want to keep a data log. There are various ways to get the time from sources on the Internet.

You may ask why not use the ESP8266 to keep time for you? Well you can, it has its own internal RTC (Real Time Clock), but the ESP8266 has 3 different operating clock frequencies - 52MHz when it boots, 80MHz during regular operation, and 160MHz if boosted. If you need more accurate time keeping, especially over longer periods, then an external RTC might provide a solution. These modules also have a battery backup in case of power loss. An RTC is not terribly accurate as it counts the time elapsed since it was set and although it may do for most applications, it may not be good enough for critical time keeping. It is possible to get the an accurate time from a SNTP time server from which the RTC can be updated at regular intervals if required.

The DS1307 Tiny RTC I2C Module (above) is an example of these items and can be purchased on Ebay and other suppliers for less than £2. There are also others like the DS1302 and DS3231 which work in a similar way and cost from 99p upwards.

The DS1307 module uses an I2C interface and for an ESP-01 should be connected as:

Vcc - 3.3v, Gnd - Gnd, SDA - D3, SCL - D4

SDA and SCL can be connected to any of the I/O pins on the larger ESP8266's (alter the code accordingly). Only the left hand side pins need to be connected on this module.

Step 1: Google Time

Picture of Google Time

There are many examples of getting the time from Google and look something like this. When you run the GoogleTime.lua program you get a result like this:

> dofile("GoogleTime.lua")
> Time: Fri, 15 Dec 2017 11:19:45 GMT

The problem with this method is that you get the time in string format and you have to split the string into its individual bits for hours, minutes, seconds etc. The RTC accepts the time in a special format i.e. UNIX time stamp. In layman's terms this is the number of seconds that have elapsed since Thursday 1st January 1970 to the present day and time. The UNIX Epoch (1970/01/01 00:00:00) is used by most computer operating systems and the elapsed time is stored as a signed 32 bit number. This means that this system will work up to 19th January 2038 when the number will become too big to store this way. One solution is to store the number as 64 bits, but for now the 32 bit method will suffice.

To set the time to 2015 July 9, 18:29:49 on the internal RTC you would use this line of code:

> rtctime.set(1436430589, 0)

The 2 parameters are seconds and micro seconds.

You can find more information reading the NodeMCU Documentation.