How to use RTC

Arduino and RTC DS3231 Easy Way

Posted on

Previously I had written an article with the title How to Use RTC DS3231 Arduino Pinout.  I used a library from RinkyDinkElektronik.com. The library is good, I can access time and set the time I want. However, there are some obstacles when I use the library, one of which I cannot synchronize with RTC with a PC.

Library

In this article, I give you a library that I just used. This library is from the pjrc.com site. I like this library because it can sync RTC with a PC. Please download this RTC library:

Download DS1307RTC Library

Please include this library into the Arduino IDE by:

  • Select Sketch menu> Include Libary> Add. ZIP Libary
  • Select libary DS1307RTC.zip Click OK

Schematic

After you enter the library into Arduino IDE, please connect your RTC to Arduino as shown below.

RTC DS3231 Arduino tutorial

 

Read Data From RTC

If RTC and Arduino are connected,  I have provided a program that can read time data from RTC DS3231 using Arduino below. Please upload this program to your Arduino.

#include <Wire.h>
#include <TimeLib.h>
#include <DS1307RTC.h>

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  tmElements_t tm;

  if (RTC.read(tm))
  {
    Serial.print("Time is : ");
    Serial.print(tm.Day);
    Serial.print("-");
    Serial.print(tm.Month);
    Serial.print("-");
    Serial.print(tm.Year);
    Serial.print(" ");
    showVal(tm.Hour);
    Serial.print(':');
    showVal(tm.Minute);
    Serial.print(':');
    showVal(tm.Second);
    Serial.println();
  }
  delay(1000);
}

void showVal(int val)
{
  if (val < 10 && val >= 0)
    Serial.print('0');
  Serial.print(val);
}

After the program has been uploaded successfully, please open the Serial Monitor on your Arduino IDE. Then you will get results like in the following picture:

 

rtc result ds3231 arduino

Program Description

  • First of all we need to enter 3 .h files, namely: Wire.h, TimeLib.h and DS1307RTC.h.
  • Library Wire.h contains data communication protocol via I2C.
  • While DS1307RTC.h provides time access on RTC.Library
  • TimeLib.h provide functions or commands relating to access time, such as Day, Month, Year, Hour, Minute, Second.
  • To access Day, Month, Year, Hour, Minute, Second we use the tmElements command. For example tm.Day, then Arduino will receive Data Day.

Hope this article is useful for all

One thought on “Arduino and RTC DS3231 Easy Way

Leave a Reply

Your email address will not be published. Required fields are marked *