The Arduino counts time from the moment it starts (millis()), but it doesn't know what time it is, and if the power goes off it returns to zero. If your project needs real time (an irrigation schedule, a dated data log, or a clock), you need an RTC (real-time clock).
And even if the power never goes off: the crystal on the Arduino board isn't designed for accuracy, so millis() can drift by seconds every hour. After a week the difference is minutes.
DS3231 or DS1307?
| DS1307 | DS3231 | |
|---|---|---|
| Accuracy | Relies on an external crystal affected by temperature, and can be minutes off per month | A built-in crystal with temperature compensation, about ±2 ppm (roughly a minute per year) at normal temperatures |
| Voltage | 5 V | 2.3 to 5.5 V |
| Extras | — | An internal temperature sensor, and two alarms |
The advice: the DS3231 costs a little more but is far more accurate.
The calculation: ±2 ppm × 31.5 million seconds in a year ≈ ±63 seconds per year. So you set it once a year and that's it.
Wiring
The I2C protocol, so just 4 wires:
| Module | Arduino Uno | ESP32 (default) |
|---|---|---|
| VCC | 5V | 3.3V |
| GND | GND | GND |
| SDA | A4 | GPIO 21 |
| SCL | A5 | GPIO 22 |
The address is 0x68. Most modules also carry a small EEPROM at another address (usually 0x57).
Watch out: 0x68 is the same address as the MPU6050. If you'll use them together, change the MPU's address to 0x69 with its AD0 pin. See troubleshooting I2C.
The code (the RTClib library)
#include <RTClib.h>
RTC_DS3231 rtc;
void setup() {
Serial.begin(9600);
rtc.begin();
if (rtc.lostPower()) {
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
DateTime now = rtc.now();
Serial.println(now.timestamp());
delay(1000);
}
The line rtc.adjust(...) sets the clock to the time the code was uploaded, once, when the battery is flat or has been removed.
That time is when the code was compiled on the computer, so it lags the real time by a few seconds (the upload time). If you need accuracy to the second, set it with a command from the Serial Monitor or from the internet.
The parts
now.hour(), now.minute(), now.day() and now.dayOfTheWeek() (zero = Sunday), and now.unixtime() gives you the number of seconds since 1970, which is the easiest way to calculate the difference between two times.
Temperature as a bonus
float t = rtc.getTemperature();
The DS3231 measures temperature in order to compensate for it, and shares it with you to about ±3 °C. It's not an accurate sensor, but useful if you want an idea of the enclosure temperature.
Example: daily irrigation at 6
int lastDay = -1;
void loop() {
DateTime now = rtc.now();
if (now.hour() == 6 && now.minute() == 0 && now.day() != lastDay) {
lastDay = now.day();
startPump(); // run the pump for 10 minutes, for example
}
}
The lastDay variable stops the condition firing 60 times during that minute. And if you want it to remember even after a power cut, save it in the EEPROM. The pump itself runs through a relay or a MOSFET.
The alarm and the SQW pin
The DS3231 has two internal alarms. When the alarm time arrives, the SQW/INT pin goes LOW. That can:
- Trigger an interrupt on the Arduino.
- Wake an ESP32 from deep sleep at an exact time, much more accurately than the ESP32's own timer.
rtc.writeSqwPinMode(DS3231_OFF); // the pin acts as an alarm
rtc.setAlarm1(DateTime(0, 0, 0, 6, 0, 0), DS3231_A1_Hour); // every day at 6:00
// and after it fires:
rtc.clearAlarm(1);
The pin is open-drain, so it needs a pull-up. Many modules have a resistor fitted.
The battery
A CR2032 battery keeps the clock running for years with the power disconnected.
An important note: some widely sold cheap DS3231 modules have a charging circuit (a resistor and diode) designed for a rechargeable battery (LIR2032). If you fit an ordinary CR2032 (non-rechargeable) and the module is powered at 5 V, that circuit will try to charge it, which isn't safe. The fix: use an LIR2032, ask someone experienced to disconnect the charging circuit, or power the module from 3.3 V.
Time from the internet
If you're using an ESP32 connected to Wi-Fi, you can get the time from the internet (NTP) without an RTC. But the RTC remains useful if the internet drops, or the project is somewhere with no Wi-Fi.
The best of both: the ESP32 gets the time from the internet once a day and writes it to the RTC. If the internet drops, the RTC carries on by itself. And mind the time zone: the internet gives you Greenwich time (UTC), and you add your country's offset, plus daylight saving if your country uses it.
Common faults
| Fault | Usual cause |
|---|---|
rtc.begin() fails | I2C wiring; run a scanner and look for 0x68 |
| The time resets to the upload time every time | The adjust line is outside the lostPower condition |
| The time resets after a power cut | The battery is flat or not seated properly |
| The year is 2165 or strange numbers | The data is corrupted; set it again |
| The time is off by a fixed number of hours | The time zone isn't set |
FAQ
How long does the battery last? While the module is powered by the Arduino, the battery isn't used at all. When the power goes off it draws microamps, so it lasts for years.
Can I build a wall clock with it? Yes, with a 7-segment display or an LCD. A nice project for beginners.