Use DS3231 RTC Module with XIAO SAMD21

Use DS3231 RTC Module with XIAO SAMD21

DS3231 is a real-time clock (RTC) module which can keep track of date and time even when a main power supply is turned off. The coin cell lithium battery is used as backup supply.

This tutorial shows how to use DS3231 RTC module with XIAO SAMD21 development board.

Components

No.ComponentQuantity
1.XIAO SAMD21 + USB-C cable1
2.DS3231 RTC module1

Circuit diagram

SCL pin of DS3231 RTC module is connected to the D5 pin on the XIAO SAMD21 board and SDA pin is connected to the D4 pin.

DS3231 RTC Module with XIAO SAMD21 (Circuit diagram)

Project setup

For project setup, the PlatformIO Core CLI tool is used. Make sure you have installed it.

  • Create a new directory for project and navigate to it:
mkdir xiao_project && cd xiao_project
  • Run the following command to initialize a new project:
pio project init --board seeed_xiao
pio pkg install --library "adafruit/RTClib"

Code

The project consists of two steps. In the first step, we initiate the RTC module and set the initial date and time when the program was compiled. It pretty easy way to set current time on the RTC module.

src/main.cpp

#include <SPI.h>
#include <RTClib.h>

RTC_DS3231 rtc;

void setup()
{
    rtc.begin();
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop() {}

Now build the project and upload the program to the development board:

pio run --target upload

Once the initial date and time was set on the RTC module, we can replace previous code to the following code:

src/main.cpp

#include <SPI.h>
#include <RTClib.h>

RTC_DS3231 rtc;
char buffer[25];

void setup()
{
    Serial.begin(115200);
    rtc.begin();
}

void loop()
{
    DateTime now = rtc.now();
    sprintf(
        buffer,
        "%04d-%02d-%02d %02d:%02d:%02d",
        now.year(),
        now.month(),
        now.day(),
        now.hour(),
        now.minute(),
        now.second()
    );
    Serial.println(buffer);
    delay(1000);
}

The code reads date and time from the DS3231 RTC module and prints data to the serial port.

Use the previous command to build project and upload program.

Testing

Connect XIAO SAMD21 via USB to a PC. Open the Serial Monitor to see date and time.

If a main power supply of DS3231 module is turned off, then the module automatically switches to the backup supply. It is a coin cell lithium battery. In that state, the DS3231 module still keeps track of date and time.

Testing DS3231 RTC Module with XIAO SAMD21

Leave a Comment

Cancel reply

Your email address will not be published.