How to use a Real Time Clock (RTC) with Arduino

14th May 2023 0 By John
How to use a Real Time Clock (RTC) with Arduino

An RTC allows you to add the element of time to your project. It uses a small IC with an oscillator and a rechargeable battery to keep track of time even when your project is powered off or reset. In this tutorial, we will explore how to connect an RTC module to an Arduino, program it and see the time printed to the console.

Materials Required:

Step 1: Hardware Setup

We are going to the the Tiny RTC DS1307 Clock Module. This communicates with the Arduino using I2C. For this tutorial we will use the Arduino Uno R3. Depending on what Arduino board you are using, you need to find the GND, 5v, SCL and SDA pins and wire them like this:

Step 2: Software Setup

  1. Download and install the Arduino IDE from the official Arduino website (https://www.arduino.cc/en/software).
  2. Launch the Arduino IDE and create a new sketch.

Step 3: Installing the RTC Library

  1. In the Arduino IDE, navigate to Sketch -> Include Library -> Manage Libraries.
  2. In the Library Manager, search for “RTC” and look for the “RTClib” library by Adafruit.
  3. Click on the “RTClib” library and click the “Install” button. You may be asked to install library dependencies if they aren’t already installed. Click INSTALL ALL.
  4. Wait for the installation to complete.

Step 4: Writing the Code

To get you started, lets use the example code in the RTClib library.

In the Arduino IDE, navigate to File -> Examples -> RTClib, then choose the example that matches your RTC module.

Lets take a look at the DS1307 example:

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include "RTClib.h" // include the library

RTC_DS1307 rtc; // setup the object, we will refer to it as rtc in the rest of the code

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; // the rtc stores the day as a number, we use this list to convert the number to the word for that day, you could shorten these words to Mon, Tues, Wed.. etc

void setup () {
  Serial.begin(57600); // setup the serial port so we can print the date and time back to the computer

#ifndef ESP8266 // this block of code only applies if you are using an ESP8266
  while (!Serial); // some devices have a native serial port like the ESP8266, wait for the serial port to connect
#endif

if (! rtc.begin()) { // start the RTC object and test the connection
    Serial.println("Couldn't find RTC"); // print a message if it does not connect
    Serial.flush(); // clear out the serial port
    while (1) delay(10); // block the code from running if the connection fails
  }

if (! rtc.isrunning()) { // test to see if the time has been set on the RTC
    Serial.println("RTC is NOT running, let's set the time!"); 
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // sync the RTC module with your computers time
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); // if you want to manually set the time, remove the // from the start and set the time
  }

  // This block allows you to set the time, like above, but on a device that is already running
  // When time needs to be re-set on a previously configured device, the
  // following line sets the RTC to the date & time this sketch was compiled
  // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // This line sets the RTC with an explicit date & time, for example to set
  // January 21, 2014 at 3am you would call:
  // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));

void loop () { // start the main loop of the code
    DateTime now = rtc.now(); // communicate with the RTC and get the current  date and time and store it in the DateTime variable 'now'

// this block prints the date and time to the serial port
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); // this line converts the day of the week number to the corresponding word from the list above
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

// this block prints the number of seconds and days since midnight 1/1/1970, also known as epoch time
    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

// this block of code shows how to offset the time 
// calculate a date which is 7 days, 12 hours, 30 minutes, and 6 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 12h + 30m + 6s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println(); // finally print a blank line
    delay(3000); // wait 3 seconds (reduce this to refresh the time quicker e.g. delay(1000);
} // repeat the loop

Step 5: Uploading and Testing

  1. Connect your Arduino Uno to your computer using a USB cable.
  2. Select the correct board and port from the Tools menu in the Arduino IDE.
  3. Click on the “Upload” button to upload the code to the Arduino.
  4. Once the upload is complete, open the Serial Monitor by clicking on the magnifying glass icon in the Arduino IDE’s toolbar or navigating to Tools -> Serial Monitor.
  5. Set the baud rate of the Serial Monitor to 57600 baud.
  6. You should see the current date and time being printed in the Serial Monitor. The time will update every second.

That’s it! You have successfully set up an Arduino Uno with an RTC module. You can now use the RTC to perform various time-related functions in your Arduino projects. Feel free to expand upon this tutorial to suit your specific needs.

For example you can isolate the individual time parts into variables by doing

Hours = now.hour();

Minutes = now.minutes();

Seconds = now.seconds();

You could then do something like, if the hour is more than 20 or less than 8 then turn a light on.

Let us know how you used this tutorial in your project in the comments below.