RTC module DS3231 - Timekeeping for Arduino

FunduinoPublished on

Datum und Uhrzeit mit DS1307 und DS3231 – auf dem LCD und im seriellen Monitor

Ein Arduino weiß nach dem Einschalten nicht, welcher Tag ist und wie spät es ist. Ein RTC-Modul (Real Time Clock) gibt ihm beides – und behält die Zeit dank einer Knopfzelle auch dann, wenn der Strom weg ist.

In dieser Anleitung baust du zuerst eine Uhr mit dem DS1307 und einem LC-Display auf, ergänzt den Wochentag und bringst danach Uhr und Display gemeinsam auf den I²C-Bus. Zum Schluss kommt der DS3231 dazu, der zusätzlich die Temperatur misst.

RTC module on a breadboard next to a Funduino UNO R3
RTC module for the Funduino UNO R3 (older device version)

You need this

1602 I2C LCD Module - 2x16 Characters, HD44780, Blue 1602 I2C LCD Module - 2x16 Characters, HD44780, Blue 3,02 € *Item no. FUN-1010568About the product — 1602 I2C LCD Module - 2x16 Characters, HD44780, Blue
DS1307 Tiny RTC module - I2C real-time clock, 5 V, backup battery DS1307 Tiny RTC module - I2C real-time clock, 5 V, backup battery 1,84 € *Item no. F23106775About the product — DS1307 Tiny RTC module - I2C real-time clock, 5 V, backup battery
Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino 11,12 € *Item no. F23107480About the product — Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino
830-point Breadboard - solderless breadboard for Arduino 830-point Breadboard - solderless breadboard for Arduino 2,90 € *Item no. FUN-1010553About the product — 830-point Breadboard - solderless breadboard for Arduino
Breadboard cables male-female - 40 pieces, 20 cm Breadboard cables male-female - 40 pieces, 20 cm 1,74 € *Item no. FUN-1010554About the product — Breadboard cables male-female - 40 pieces, 20 cm

All 5 parts together 20,62 € *Ready to ship immediately · Delivery time: 1-3 business days

* All prices include statutory VAT, plus shipping costs.

What an RTC module is for

As soon as you turn on the Arduino, it can measure the time that has elapsed since then. But it doesn’t know the current date and time - for that, you need an RTC module (Real Time Clock). Set the date and time once when you first start it; after that, the module’s coin-cell battery keeps the clock running even when the Arduino is turned off.

Real-time clocks are found in many everyday devices:

  • in computers: The RTC provides the operating system with the date and time
  • in household appliances: Real-time clocks control cooking processes or show the remaining time on a washing machine
  • in heating controls: summer and winter modes, day-night switching, setting heating periods throughout the day
  • for recording and storing working hours at a company
  • in payment systems: the date and time are printed on the receipt

In this guide, you’ll first work with the DS1307 and an LCD. At the end, you’ll learn about the DS3231, which can also measure temperature.

RTC module with inserted button cell
An RTC module with a button cell battery
Applications of real-time clocks
Real-time clocks are built into many everyday devices.
1 / 2

Build the circuit

You wire up the LCD in basically the same way as in the LCD module instructions. Then connect the RTC module: connect it to 5V and GND, connect SDA to analog input A4, and SCL to A5.

On the MEGA2560 R3, SDA and SCL have dedicated connections on the board: pins 20 and 21.

Schematic with RTC module and LCD on Arduino UNO R3
Schematic: RTC module and LCD on the UNO R3
RTC module on a breadboard next to a Funduino UNO R3
RTC module for the Funduino UNO R3 (older device version)
Arduino MEGA2560 R3 with highlighted SDA and SCL pins
On the MEGA2560 R3, SDA and SCL are on pins 20 and 21.
1 / 3

Install the libraries and set the clock

Before you can program, you need two libraries:

Add both in the Arduino IDE via Sketch › Include Library › Add .ZIP Library and select the downloaded file.

Next, upload the “Set Time” sketch. It transfers the date and time from the device connected to the microcontroller to the real-time clock. You can find it under File › Examples › DS1307RTC › SetTime. After that, you can move on to the actual sketch.

The DS1307 real-time clock does not keep time to the exact second. About 15 seconds pass between uploading the set-time sketch and uploading the final sketch, and the RTC cannot compensate for this difference.

Display time and date

The sketch gets the time and date from the RTC and outputs both in two places: in the serial monitor and on the LCD. The printDigits function at the end ensures that numbers below 10 get a leading zero in the serial monitor.

Display the time and date on an LCD (DS1307)
#include <Wire.h>
#include <LiquidCrystal.h>
#include <time.h>
#include <DS1307RTC.h>

// Here, we specify which pins on the microcontroller board are used for the LCD.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  // In setup, we specify how many characters and lines are used.
  lcd.begin(16, 2);
  // Opens the serial port and sets the baud rate (9600) for transmission.
  Serial.begin(9600);
  // This function retrieves the time and date from the RTC.
  setSyncProvider(RTC.get);
}

void loop()
{
  // Serial.print displays something in the serial monitor:
  // hour, minute, second, space, day, space, and so on.
  Serial.print(hour());
  // For minutes and seconds, printDigits is used,
  // which is defined at the end of the sketch.
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();

  delay(1000);  // wait one second

  // setCursor specifies where the text should begin:
  // here, at the third character in the first line.
  lcd.setCursor(2, 0);
  lcd.print(hour());
  lcd.print(":");
  lcd.print(minute());
  lcd.print(":");
  lcd.print(second());
  lcd.print(" ");

  // The word "o'clock" appears after the time. This is followed by three spaces;
  // otherwise, an extra "r" would remain after "o'clock" for numbers below 10: the
  // LCD library has no command that adds a leading 0 to numbers below 10.
  lcd.print("o'clock");
  lcd.print(" ");
  lcd.print(" ");
  lcd.print(" ");

  // The next text begins at the second character in the second line.
  lcd.setCursor(1, 1);
  lcd.print(day());     // The date is displayed as
  lcd.print(".");       // "day"."month"."year".
  lcd.print(month());
  lcd.print(".");
  lcd.print(year());
}

// Here, we specify that numbers below 10 are automatically preceded by a 0
// in the serial monitor. This applies only to the serial monitor, not the LCD.
void printDigits(int digits)
{
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Extension: Display weekday

You can also display the day of the week before the date. To do this, add the command to the lcd.print section before the date: printDay(); and add this section after the loop function:

Extension: Display weekday
// Hier wird für den vorher im Sketch verwendeten Befehl printDay festgelegt, was er tut.
void printDay()
{
  int wochentag;
  wochentag = weekday();  // Der Wochentag ergibt sich aus dem Datum.

  if (wochentag == 1) { lcd.print("So, "); }  // Tag 1 ist Sonntag,
  if (wochentag == 2) { lcd.print("Mo, "); }  // Tag 2 ist Montag und so weiter.
  if (wochentag == 3) { lcd.print("Di, "); }
  if (wochentag == 4) { lcd.print("Mi, "); }
  if (wochentag == 5) { lcd.print("Do, "); }
  if (wochentag == 6) { lcd.print("Fr, "); }
  if (wochentag == 7) { lcd.print("Sa, "); }
}

Two I²C components at once: Change the LCD address

If you want to operate the RTC module and the LCD together on the I²C bus, both components need different I²C addresses. The real-time clock’s address is fixed and cannot be changed, so you’ll need to change the display’s address.

This is only possible if your I²C module has the three solder pads A0, A1, and A2 on the back. By default, all three are disconnected. Connecting them in a different combination changes the display’s HEX address - the table shows which combination results in which address (I = connected, : = not connected).

You may already know the HEX code scanner from our guide “Control two displays simultaneously with an I2C module.” It lets you easily read the current address of your I²C module.

Back of an I2C module with solder bridges A0, A1, and A2
The solder pads A0, A1, and A2 on the back of the I²C module
Table of possible solder jumper combinations and their corresponding I2C addresses
Overview: which bridges lead to which HEX address
1 / 2

Display the time on an I²C LCD

In addition to Time and DS1307RTC, you need version 1.3.4 of the NewLiquidCrystal library for the I²C display. You can get it from the project’s download section. Add all three again via Sketch › Include Library › Add .ZIP Library.

Here, too, first upload the “Set Time” sketch to set the clock. Then enter your display’s HEX address at the top of the sketch - in this example, it’s 0x3D.

Circuit diagram with I2C LCD and RTC module on the same I2C bus
Wiring diagram: I²C LCD and RTC module connected to the Arduino together
Displaying the time and date on an I²C LCD (DS1307)
// Load libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <time.h>
#include <DS1307RTC.h>

// Name the I²C display and enter its HEX address (here 0x3D).
LiquidCrystal_I2C lcd(0x3D, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup()
{
  lcd.begin(16, 2);   // Start the display: 16 characters in 2 lines
  lcd.backlight();    // Turn on the display backlight
  Serial.begin(9600); // Start the serial connection at a baud rate of 9600
  setSyncProvider(RTC.get);  // Retrieve data from the RTC
}

void loop()
{
  // Output in the serial monitor:
  // Hour, minute, second, space, day, space, and so on.
  Serial.print(hour());
  // For minutes and seconds, printDigits is used,
  // which is defined at the end of the sketch.
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();

  delay(1000);  // wait one second

  // setCursor specifies where the text should begin:
  // here, at the third character in the first line.
  lcd.setCursor(2, 0);
  lcd.print(hour());   // The time appears in the format
  lcd.print(":");      // hours:minutes:seconds.
  lcd.print(minute());
  lcd.print(":");
  lcd.print(second());
  lcd.print(" ");
  lcd.print("Clock");    // The word "Clock" appears after it.
  lcd.print(" ");
  lcd.print(" ");
  lcd.print(" ");

  // The date appears on the second line.
  lcd.setCursor(1, 1);
  lcd.print(day());
  lcd.print(".");
  lcd.print(month());
  lcd.print(".");
  lcd.print(year());
}

// The printDigits command for the serial monitor
void printDigits(int digits)
{
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

The DS3231: also measure the temperature

In addition to the date and time, the DS3231 module can also measure temperature. For this, you need a different library: RTClib. You can find it directly in the library manager under Sketch › Include Library › Manage Libraries.

In the sketch, the line with rtc.adjust(…) is initially commented out. To set the clock, uncomment it once, enter the date and time, and upload the sketch. Then comment it out again - otherwise, the clock will be reset to the same time every time you restart.

The serial monitor will then display a line with the date, time, and temperature every second.

Library management in the Arduino IDE with the RTClib library
The RTClib library in the Library Manager
Serial monitor with date, time, and DS3231 temperature value
Date, time, and temperature in the serial monitor
1 / 2
DS3231: Date, time, and temperature in the serial monitor
// Include the required library
#include <RTClib.h>

// Name of the RTC module (rtc)
RTC_DS3231 rtc;

void setup()
{
  // Start the RTC module
  rtc.begin();
  Serial.begin(9600);

  /*
    If the date and time are incorrect: set the date and time.
    Order: year, month, day, hour, minute, second
    Example: August 31, 2022, 10 hours, 31 minutes, 30 seconds

    rtc.adjust(DateTime(2022, 8, 31, 10, 31, 30));
  */
}

void loop()
{
  // rtc.now() gets the current time
  DateTime aktuell = rtc.now();

  /*
    Set the date format
    DD   -> day with leading 0
    MM   -> month with leading 0
    YYYY -> full year
  */
  char Datum[] = "DD.MM.YYYY ";
  // Convert the date to a string and display it
  Serial.print(aktuell.toString(Datum));

  // Set the time format
  char Zeit[] = "hh:mm:ss";
  // Convert the time to a string and display it
  Serial.print(aktuell.toString(Zeit));

  // Get the temperature
  String Temperatur = String(rtc.getTemperature());
  // The value uses the Anglo-Saxon number format:
  // replace the period with a comma
  Temperatur.replace(".", ",");
  Serial.println(" Temperature: " + Temperatur + "°C");

  // Pause for 1 second
  delay(1000);
}
Rate the instructions

Comments

Ask a question or share an experience

Contact us if something doesn’t work. Please include your board and the error message.

We review every comment before publication. Your email address remains with us.