MySQL for the Internet of Things

(Steven Felgate) #1

Chapter 4 ■ Data transformation


There is a bit of code needed to initialize the RTC, but it isn’t difficult. First, we must download the RTC
library. You can find an excellent library to use at https://github.com/adafruit/RTClib. Download the
library by clicking the Download Zip button, unzip the archive, and then copy the folder to your Arduino/
Library folder. You may need to rename the folder. I recommend using RTCLib for the folder name.


■Tip if you copied the library while the arduino iDe was open, you may need to restart the iDe for it to


recognize the library.


Once the library is ready, we can add the code to use the library. We need to include the library header
and define an instance of the RTC class. The following are the lines of code needed:


#include "RTClib.h"
...
RTC_DS1307 rtc; // real time clock


Next, we need to initialize the RTC class with the begin() method, and if the module has not been
used before or if you have changed the battery, we also need to set the time with the adjust() method. The
following is the code you can use to accomplish both of these tasks:


...
rtc.begin();
if (!rtc.begin()) {
Serial.println("Couldn't find the RTC module.");
while (1);
}


if (!rtc.isrunning()) {
Serial.println("ERROR: The RTC module is not working.");
} else {
// Comment out this line after the first run, it is only needed for setting
// the date and time for the first time.
rtc.adjust(DateTime(F(DATE), F(TIME)));
}


Notice the parameters passed to the method rtc.adjust(). This converts the values of the current date
and time to a DateTime class, which the method needs to set the date and time for the module. The DATE
and TIME are macros that retrieve the date and time from your system at the point when the sketch is
compiled. Thus, you need to call this method only when you first start using the RTC. You do not need to call it
every time you run your sketch. If you do, you will be setting the RTC to the same values every time. This is not
what you want. Thus, I’ve written the code so that you can comment out the method after the first compilation.
Now let’s see how to use the RTC in a sketch to capture the date and time on an Arduino.


Code Implementation


The code to add the date and time to the row written to the file requires a bit more work than you may
expect. The RTC module provides primitives for getting the separate elements of a date and time such as
month, year, hour, and so on. Thus, we need to get these values and combine them into a format we expect
to see. In this case, we want to see a format of month/day/year hour:minute:seconds. Listing 4-4 shows code
to get and format the date and time.

Free download pdf