0% found this document useful (0 votes)
62 views

L48 Real Time Clock

The document discusses using a real-time clock module with an Arduino to provide timekeeping capabilities. It describes connecting a DS1307 RTC breakout board to an Arduino and using the RTClib library to set and read the clock time. Code examples are provided to initialize the RTC, get the current time, and calculate times in the future. The document then discusses improving a previous logging sketch by adding time stamps to data written to an SD card, combining the RTC and SD card modules.

Uploaded by

Mishal Islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

L48 Real Time Clock

The document discusses using a real-time clock module with an Arduino to provide timekeeping capabilities. It describes connecting a DS1307 RTC breakout board to an Arduino and using the RTClib library to set and read the clock time. Code examples are provided to initialize the RTC, get the current time, and calculate times in the future. The document then discusses improving a previous logging sketch by adding time stamps to data written to an SD card, combining the RTC and SD card modules.

Uploaded by

Mishal Islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Peter Dalmaris Lecture 47 Arduino Step by Step

Real time clock


The Arduino, even though it can interact with its environment, can’t do anything at all
without a access to sensors and all kinds of components. And unlike most computers you
are used to, it cannot tell the time. Although knowing the time is not needed in many
applications (and indeed, we have not really needed it up to now), sooner or later you will
come across a project where knowing the time is a requirement.

It is true that the Arduino has a build-in sense for time. It knows how much time has passed
since it started executing a program. You can use the millis() function to get a number that
represents this time in milliseconds. A similar function is micros(), and it does the same
thing as millis() except that it reports the elapsed time in microseconds instead of
milliseconds. There are also the time-related functions delay() and delaymicroseconds()
which add a delay in your program, the fist in milliseconds and the second in
microseconds.

Still, your sketch cannot ask the Arduino for the time. You could use an Internet time server
and poll it occasionally for the time, but this method requires Internet connectivity, a
dependency that maybe an overkill for some projects.

A real-time clock break out board is a PCB that contains a time-keeping integrated circuit.
It’s like the watch you wear on your wrist. You glance at it to get the time. The Arduino will
be able to ask the real-time clock for the time too.

A simple application for a real-time clock is for time-stamping log entries recorded on an
SD card. We will look at this problem in this lecture. You can also consider applications
where certain events must be scheduled, like turning an illuminated sign on and off, or
taking sensor readings at predetermined times.

1
Peter Dalmaris Lecture 47 Arduino Step by Step

Demo 1: Setting and reading the clock


In this demo, I’ll show you how to use a
typical real time clock with your Arduino. I will
be using the DFRobot DS1307 RTC breakout,
EEPROM Clock
which I purchased on eBay for around $4.
This device, like many others, is based on the
popular DS1307 clock IC, and it can do
anything you would expect a good clock can
do. It counts seconds, minutes, hours, days,
years, goes up to 2100 and compensates for
leap years.

It also consumes very little power, 500nAmps,


which when using the on-board battery gives
the device a life of around 5 years (although I
have not tested this claim!).

The breakout also features an additional IC in


which you can store up to 4kbytes of data
(EEPROM 24C32), and an integrated
temperature sensor. Not bad at all for such a low cost device!

Let’s do the wirings and connect the


breakout to the Arduino. The RTC uses the
IC2 serial bus for communication.
Therefore, we only need two wires for Vcc
and Gnd, one wire for data (SDA), and one
for the synchronisation clock (SCL). On the
Arduino Uno, the SDA pin is analog 2, and
the SCL pin is 1. In you have any other
board, you may want to check the location
of the SDA and SCL pins against your
board’s documentation before you do the
connections.

Before looking at the sketch, let’s install the


library for the device. If you are using the
TinyRTC breakout, you can download the
library from the manufacturer’s web site.
This clone from Adafruit also seems to be
working (thank you to Matt Hill for letting
me know about this).

2
Peter Dalmaris Lecture 47 Arduino Step by Step

Download it, copy the library folder to the Arduino libraries folder, and restart the IDE. Then,
load the sketch from File —> RTClib —> ds1307.

This is what you will see (slightly edited to improve readability):

#include <Wire.h>
 Import the Wire library so that we can use the IC2 bus.
#include "RTClib.h"
Import the RTClib library so that we can use the clock.
RTC_DS1307 rtc; Declare an RTC_DS103 object, name it “rtc”.

void setup () {

Serial.begin(9600);
 Initialise the IC2 bus.
Wire.begin();

Initialise the real time clock device.
rtc.begin();

if (! rtc.isrunning()) {
 This will get the time from your
Serial.println("RTC is NOT running!");
 computer during compilation
rtc.adjust(DateTime(2014,01,16,14,45,00));
 and automatically set the time.
// following line sets the RTC to the date & time this sketch was compiled

//RTC.adjust(DateTime(__DATE__, __TIME__));

}
 This will adjust the time with the
} help of the C-language DateTime Check to determine is the device is on. Since the
object initialiser. device is powered by a battery when the Arduino is
off, it will continue to keep track of time and be in a
void loop () {

“running” state. As long as a time has been set and
DateTime now = rtc.now();
 the battery can power it, the “rtc.isrunning()”
Serial.print(now.year(), DEC);
 function will return true. The only time you will
Serial.print('/');
 probably see a “false” returned is when you run this
sketch for the very first time.
Serial.print(now.month(), DEC);

Serial.print('/');
 Get the time now, and store it in the “now” variable,
Serial.print(now.day(), DEC);
 which is of time DateTime.
Serial.print(' ');

Print time attributes to the Serial port.
Serial.print(now.hour(), DEC);

Serial.print(':');

Serial.print(now.minute(), DEC);

Serial.print(':');

Serial.print(now.second(), DEC);

Serial.println();

Serial.print(" since midnight 1/1/1970 = ");

Serial.print(now.unixtime());
 Get the number of seconds elapsed since 1/1/1970,
Serial.print("s = ");
 when Unix time begins.
Serial.print(now.unixtime() / 86400L);

… and convert that to days, since 1 day
Serial.println("d");
 contains 86400 seconds.

… sketch continues in next page…

3
Peter Dalmaris Lecture 47 Arduino Step by Step

// calculate a date which is 7 days and 30 seconds into the future



DateTime future (now.unixtime() + 7 * 86400L + 30);

Serial.print(" now + 7d + 30s: ");

Serial.print(future.year(), DEC);
 Create a new object of type DateTime,
Serial.print('/');
 name it future and initialise it with a
date that is 7 days and 30 second into
Serial.print(future.month(), DEC);

the future.
Serial.print('/');

Serial.print(future.day(), DEC);

Serial.print(' ');
 Print future attributes to the Serial port.
Serial.print(future.hour(), DEC);

Serial.print(':');

Serial.print(future.minute(), DEC);

Serial.print(':');

Serial.print(future.second(), DEC);

Serial.println();

Serial.println();

delay(3000);

}

Once the clock has been set, it will keep the time independently of the Arduino,
compensating for leap years and the like until its onboard battery fails. All you have to do in
order to get a reading of the time is to call the now() function, which returns a DateTime
object.

Upload this sketch, and open


the monitor. You should see
something like this:

! Current time reported by the RTC

!
Results of time/date calculations

4
Peter Dalmaris Lecture 47 Arduino Step by Step

Demo 2: Logging with time stamps


Back in Lecture 39, you learn about how to
use an SD card for logging sensor
readings. Let’s go ahead and improve the
design from Demo 2 so that the time of
data capture is also stored in your SD card.

Here’s the new and improved circuit. It is a


merge between Lecture 39 Demo 2 and
this lecture’s Demo 1.

If you guessed that the sketch is also


mostly a merge between these two, you
guessed correctly.

For the SD card module connections, I


remind you the pins for the Arduino Uno:

• MOSI on digital pin 11

• MISO on digital pin 12

• CLK on digital pin 13

• CS can vary, but to keep things tidy I use


digital pin 10.

• Power: some boards work with either


3.3V or 5V, or both. The one I use in this demo works with both, and I connected it to the
5V pin on the Arduino. Be careful in case yours only accepts 3.3V to not connect it to the
5V pin on the Arduino!

• Ground: connect to a GND pin on the Arduino.

In the next page, I provide the merged sketch, and comments to the interesting segments.

…please see next page…


5
Peter Dalmaris Lecture 47 Arduino Step by Step

#include <SD.h>
 Include the SD card library.


#include <Wire.h>

#include "RTClib.h" Include the IC2 library for the real time clock.

RTC_DS1307 rtc;
 Import the RTClib library so that we can use the
const int chipSelect = 10; clock breakout library.

void setup() { 
 Instead of manually setting the time like in Demo


1, this syntax will get the date and time from
Serial.begin(9600);
 your computer during compilation time, and
Wire.begin();
 reset the RTC every time the sketch is uploaded.
rtc.begin(); 

rtc.adjust(DateTime(__DATE__, __TIME__));

Serial.print("Initializing SD card...");

pinMode(10, OUTPUT);

if (!SD.begin(chipSelect)) {

Serial.println("Card failed, or not present");

return;

}

Serial.println("card initialized.");

}

void loop(){

DateTime now = rtc.now();
 Get the sensor readings.
String dataString = "";

for (int analogPin = 0; analogPin < 2; analogPin++) {

int sensor = analogRead(analogPin);

dataString += String(sensor);

if (analogPin < 1) {

dataString += ","; 

}

}

File dataFile = SD.open("datalog.txt", FILE_WRITE); 

if (dataFile) { 

print_time(now, dataFile);
 Get a handle to the datalog file.
dataFile.println(dataString);

Call the print_time function which will
dataFile.close();
 produce the timestamp. Pass a reference
Serial.println(dataString);
 to the now object that contains the
} 
 current time, and the datafile object
which contains a handle to the data file.
else {

Serial.println("error opening datalog.txt”)

} 

Print the sensor readings to the data file.
delay(3000);

}

… continues next page …

6
Peter Dalmaris Lecture 47 Arduino Step by Step

void print_time(DateTime capture_time, File file)



{

file.print(capture_time.year(), DEC);
 This function accepts a DateTime
object which contains the current date
file.print('/');
 and time, and a File object with
file.print(capture_time.month(), DEC);
 contains a handle to the file we want
file.print('/');
 to print the timestamp.
file.print(capture_time.day(), DEC);

file.print(' ');
 Print the current date and time one
file.print(capture_time.hour(), DEC);
 element at a time, to the data file.
file.print(':');

file.print(capture_time.minute(), DEC);

file.print(':');

file.print(capture_time.second(), DEC);

file.print(',');

}

There is nothing new in this sketch, just a recombination of known elements. You now have
a way to create a data-logger, which can work in remote locations, on a battery which can
be charged by a small solar panel.

An exercise
With the right hardware, keeping time is easy. Try out this exercise:

!
Create an LCD clock. Use a real time clock like the one in this lecture, combine it with an LCD
screen, and display the date and time on it.

!
For the adventurous, here’s another exercise: Extend the LCD clock so that it has these features:

!
1. A toggle switch

2. One rotary potentiometer

3. A buzzer

4. Only keeps track of time (don’t worry about the date for now)

!
The toggle switch will set the mode of the clock to Time Set or Alarm set. When the toggle switch is
on, then turning the potentiometer will change the time. When the switch is off, then turning the
potentiometer will change the alarm time.

!
Assuming the clock keeps time in 24 hour format, make your gadget so that when the alarm time is
reached, a sound will be generated by the buzzer for 10 seconds.

You might also like