The DS3231 is a highly accurate, low-cost real-time clock (RTC) module with an integrated temperature-compensated crystal oscillator (TCXO) and crystal. It maintains seconds, minutes, hours, day, date, month, and year information, with automatic adjustment for leap years and months with fewer than 31 days. The module communicates with a microcontroller via I2C protocol.
Pin Number | Name | Description |
---|---|---|
1 | VCC | Power supply (2.3V to 5.5V) |
2 | GND | Ground connection |
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);
// Check if the RTC is connected correctly
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
// Check if the RTC lost power and if so, set the time
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();
// Print the current date and time
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);
}
Wire
library's setClock()
function to adjust I2C clock speed if communication issues arise.