The DS3231 Real Time Clock (RTC) module is a low-cost, extremely accurate I2C real-time clock with an integrated temperature-compensated crystal oscillator (TCXO) and crystal. The module maintains seconds, minutes, hours, day, date, month, and year information, with automatic leap year compensation valid up to 2100. It is commonly used in electronics projects where time tracking is essential, such as data loggers, clocks, and access systems.
Pin Number | Pin Name | Description |
---|---|---|
1 | VCC | Power supply (2.3V to 5.5V) |
2 | GND | Ground |
3 | SDA | Serial Data Line for I2C communication |
4 | SCL | Serial Clock Line for I2C communication |
5 | SQW | Square Wave/Interrupt Output |
6 | 32K | 32kHz Output |
7 | RST | Reset Input (Active Low) |
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;
void setup() {
Serial.begin(9600);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, let's set the time!");
// The following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
DateTime now = rtc.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
delay(1000);
}
Note: This example uses the RTClib
library, which can be installed via the Arduino Library Manager. The code initializes the DS3231 RTC and prints the current time to the Serial Monitor every second. If the RTC has lost power, it will set the time to the time the sketch was compiled.