How to Make Clock and Calendar on Arduino with RTC DS1307 and DS3231

Introduction

Welcome to the world of clock and calendar integration with Arduino! In this guide, we’ll explore How to Make Clock and Calendar on Arduino with RTC DS1307 and DS3231 real-time clock (RTC) modules such as the DS1307 and DS3231. RTC modules provide accurate timekeeping functionality, allowing Arduino projects to maintain precise time and date information even when disconnected from power. Let’s delve into the details of RTC real-time clocks and learn how to integrate them with Arduino to build a clock and calendar system.

Hardware Required

You will require the following Hardware Components for How to Make Clock and Calendar on Arduino with RTC DS1307 and DS3231.

Components#Buy From Amazon
Arduino UNO1Buy Link
DS3231 RTC Real Time Clock Module1Buy Link
DS1307 RTC Real Time Clock Module1Buy Link
9v DC Adapter (Optional)1Buy Link
Jumper Wires8Buy Link
Breadboard1Buy Link

What is an RTC Real-Time Clock?

Real-time clocks (RTCs) provide time measurements in units like seconds, minutes, hours, days, weeks, months, and years. Unlike standard clocks that count pulses, RTCs resemble conventional clocks and calendars we use daily.

They feature a crystal resonator and electronics to track time accurately, considering factors like the sexagesimal system and leap years. Common RTCs include the DS1307 and DS3231, both offering communication via the I2C bus.

The DS3231, with its temperature compensation, offers higher precision compared to the DS1307, which may lag by up to 1-2 minutes per day. DS3231 ensures accuracy within 2ppm, equivalent to 1-2 seconds per month.

These modules often include an EEPROM for data storage and a CR2032 battery for power backup. RTCs find applications in various electronics projects, including light and irrigation system timers, dataloggers, and power management for Arduinos.

Pinout of DS3231 RTC Module

DS3231-RTC-Real-Time-Clock-Module-Pinout

Pin Configuration of DS3231 RTC Module

NoPin NameDescription
1VCCConnected to Positive of power source
2GNDConnected to Ground.
3SDASerial Data pin (I2C interface)
4SCLSerial Clock pin (I2C interface)
5SQWSquare Wave Output
632K32K oscillator output

Pinout of DS1307 RTC Module

DS1307-RTC-Real-Time-Clock-Module-Pinout

Pin Configuration of DS3231 RTC Module

NoPin NameDescription
1VCCConnected to Positive of power source
2GNDConnected to Ground.
3SCLSerial Clock pin (I2C interface)
4SDASerial Data pin (I2C interface)
5SQWSquare Wave Output
6DSData/Address Select
7BATBattery Backup Power Input

Specifications

  1. Accuracy:
    • Specifies the precision of timekeeping, typically measured in parts per million (PPM) or seconds per day.
  2. Operating Voltage:
    • Defines the voltage range required for the RTC module to operate properly.
  3. Interface:
    • Indicates the communication interface used to connect the RTC module to Arduino (e.g., I2C, SPI).
  4. Backup Power Source:
    • Describes the type and capacity of the backup power source (e.g., coin cell battery) used to maintain timekeeping functionality during power loss.
  5. Temperature Range:
    • Specifies the operating temperature range within which the RTC module can maintain accurate timekeeping.

Features

  1. Battery Backup:
    • Provides backup power to the RTC module to ensure continuous timekeeping even when the main power source is disconnected.
  2. Low Power Consumption:
    • Designed for low power operation, minimizing energy consumption and extending battery life.
  3. Adjustable Clock Output:
    • Allows for the configuration of clock output frequencies to suit specific application requirements.
  4. Alarm Functionality:
    • Offers alarm features for scheduling events or triggering actions based on specific time or date conditions.
  5. Integrated Temperature Compensation:
    • Includes temperature compensation mechanisms to maintain accurate timekeeping across varying environmental conditions.

Circuit Diagram

The following circuit shows you the connection of the How to Make Clock and Calendar on Arduino with RTC DS1307 and DS3231. Please make the connection carefully

Arduino Clock and Calendar DS3231 Precision RTC Real Time Clock Module Circuit

Arduino-Clock-and-Calendar-DS3231-Precision-RTC-Real-Time-Clock-Module-Circuit

Arduino Clock and Calendar DS1307 RTC Real Time Clock Module Circuit

Arduino-Clock-and-Calendar-DS1307-RTC-Real-Time-Clock-Module-Circuit

Circuit Connections

ArduinoDS3231 ModuleDS1307 Module
5VVCC PinVCC Pin
GNDGND PinGND Pin
A4SDASDA
A5SCLSCL

Installing Arduino IDE Software

First, you will require to Download the updated version of Arduino IDE Software and Install it on your PC or laptop. if you Learn How to install the Arduino step-by-step guide then click on how to install Arduino Button given Blow

Installing Libraries

Now when you are Ready to upload the code, to the Arduino Board you will need first to add the Following Libraries in Arduino, If you Learn How to add the library in the Arduino step-by-step guide click on how to install the library Button given Blow

Code Examples

Get the date and time:

The initial example demonstrates utilizing an RTC to retrieve current date and time data, which is then displayed through the serial port. It also illustrates setting the date and time, along with detecting power loss.

//For more Projects: www.arduinocircuit.com

#include <Wire.h>
#include "RTClib.h"

// RTC_DS1307 rtc;
RTC_DS3231 rtc;

String daysOfTheWeek[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
String monthsNames[12] = { "January", "February", "March", "April", "May", "June", "July","August","September","October","November" ,"December" };

void setup() {
  Serial.begin(9600);
  delay(1000);

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

  // If power is lost, set date and time
  if (rtc.lostPower()) {
    // Set to compilation date and time
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    
    // Set to specific date and time. In the example, January 21, 2016 at 03:00:00
    // rtc.adjust(DateTime(2016, 1, 21, 3, 0, 0));
  }
}

void printDate(DateTime date)
{
  Serial.print(date.year(), DEC);
  Serial.print('/');
  Serial.print(date.month(), DEC);
  Serial.print('/');
  Serial.print(date.day(), DEC);
  Serial.print(" (");
  Serial.print(daysOfTheWeek[date.dayOfTheWeek()]);
  Serial.print(") ");
  Serial.print(date.hour(), DEC);
  Serial.print(':');
  Serial.print(date.minute(), DEC);
  Serial.print(':');
  Serial.print(date.second(), DEC);
  Serial.println();
}

void loop() {
  // Get current date and display by Serial
  DateTime now = rtc.now();
  printDate(now);

  delay(3000);
}

Scheduled on and off:

The following example presents a common project where an RTC is utilized to activate or deactivate a device at a specific time and date. For instance, it can be employed to regulate garden irrigation, lighting, heating, deploy an awning, or control any other device using a relay.

The IsScheduledON function manages the power state, turning it on or off. In this instance, the activation is scheduled for Wednesdays, Saturdays, and Sundays from 09:30 to 11:30 and from 21:00 to 23:00. By adjusting the contents of this function, you can program the desired on and off conditions.

//For more Projects: www.arduinocircuit.com

#include <Wire.h>
#include "RTClib.h"

const int outputPin = LED_BUILTIN;
bool state = false;

// RTC_DS1307 rtc;
RTC_DS3231 rtc;

void setup() {
  Serial.begin(9600);
  delay(1000);

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

  if (rtc.lostPower()) {
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
}

// Check if the ignition is programmed
bool isScheduledON(DateTime date)
{
  int weekDay = date.dayOfTheWeek();
  float hours = date.hour() + date.minute() / 60.0;

  // From 09:30 to 11:30 and from 21:00 to 23:00
  bool hourCondition = (hours > 9.50 && hours < 11.50) || (hours > 21.00 && hours < 23.00);

  // Wednesday, Saturday or Sunday
  bool dayCondition = (weekDay == 3 || weekDay == 6 || weekDay == 0);
  if (hourCondition && dayCondition)
  {
    return true;
  }
  return false;
}

void loop() {
  DateTime now = rtc.now();

  if (state == false && isScheduledON(now)) // Off and should be on
  {
    digitalWrite(outputPin, HIGH);
    state = true;
    Serial.print("Enabled");
  }
  else if (state == true && !isScheduledON(now)) // On and should be off
  {
    digitalWrite(outputPin, LOW);
    state = false;
    Serial.print("Disable");
  }

  delay(3000);
}```

### Datalogger with RTC
The following example shows another very common case, the use of an RTC to generate a Datalogger, that is, a device that periodically records the measurement of a sensor. In the example, we will use a [SD card](/arduino-micro-sd-card/) to save the values.

Simply, we obtain the date, time, and value of the sensor, which in the example we simulate with the readSensor() function, and we save the data on the card with the logValue(,,) function.

In a real project we could save one or more measurements, separated by commas, for example. We could also vary the time of the measurement, which in the example is carried out every 10 seconds, for example, when an event occurs, or at certain times of the day using the RTC itself.
```cpp
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"

File logFile;

// RTC_DS1307 rtc;
RTC_DS3231 rtc;

void setup()
{
  Serial.begin(9600);
  Serial.print(F("Starting SD..."));
  if (!SD.begin(4))
  {
    Serial.println(F("Error starting"));
    return;
  }
  Serial.println(F("Started successfully"));
}

// Function that simulates the reading of a sensor
int readSensor()
{
  return 0;
}

void logValue(DateTime date, int value)
{
  logFile.print(date.year(), DEC);
  logFile.print('/');
  logFile.print(date.month(), DEC);
  logFile.print('/');
  logFile.print(date.day(), DEC);
  logFile.print(" ");
  logFile.print(date.hour(), DEC);
  logFile.print(':');
  logFile.print(date.minute(), DEC);
  logFile.print(':');
  logFile.print(date.second(), DEC);
  logFile.print(" ");
  logFile.println(value);
}

void loop()
{
  // Open file and write value
  logFile = SD.open("datalog.txt", FILE_WRITE);

  if (logFile) {
    int value = readSensor();
    DateTime now = rtc.now();

    logValue(now, value);
    logFile.close();

  }
  else {
    Serial.println(F("Error opening file"));
  }
  delay(10000);
}

Applications

  1. Clock and Calendar Systems: Use RTC modules to build clock and calendar systems for displaying and tracking time and date information in various applications, including digital clocks, calendars, and scheduling devices.
  2. Data Logging: Integrate RTC modules into data logging systems to timestamp recorded data and maintain accurate time records for analysis and archival purposes.
  3. Automation and Control: Incorporate RTC modules into automation and control systems to schedule tasks, events, or operations based on specific time or date criteria.
  4. IoT (Internet of Things) Devices: Utilize RTC modules in IoT devices to synchronize timekeeping and enable time-sensitive functionality, such as scheduling sensor readings or transmitting data at specific intervals.
  5. Security Systems: Integrate RTC modules into security systems for time-stamping access logs, recording surveillance footage, and scheduling security protocols based on time of day or day of week.

Conclusion

By leveraging RTC modules like the DS1307 and DS3231, Arduino projects can benefit from accurate and reliable timekeeping functionality, enabling the implementation of various time-sensitive applications and functionalities. Whether you’re building a digital clock, scheduling tasks, logging data, or automating processes, RTC real-time clocks provide the essential timekeeping infrastructure for Arduino-based projects. Let’s harness the power of RTC modules and Arduino to create innovative clock and calendar systems tailored to our specific needs and requirements!

Leave a Comment


error: