DS3231 real-time clock on I2C, on an Arduino Uno
A DS3231 clock module on A4 and A5 keeps the date and time; RTClib reads it once a second and prints the date, the time and the day of the week. The whole build, an Arduino Uno and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $30. On Mokxi they're free.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// A DS3231 real-time clock: the date and time, kept by the module.
//
// DS3231 SDA -> A4 SCL -> A5 VCC -> 5V GND -> GND
//
// The DS3231 counts seconds on its own temperature-compensated crystal, and
// a coin cell on a real module keeps it counting with the board unplugged.
// RTClib asks it for the time over I2C.
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;
const char DAYS[7][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
void print2(int value) {
if (value < 10) Serial.print('0');
Serial.print(value);
}
void setup() {
Serial.begin(9600);
Serial.println("Mokxi Uno: DS3231 on A4 and A5");
if (!rtc.begin()) {
Serial.println("no clock found: check SDA and SCL");
while (true) {
}
}
}
void loop() {
DateTime now = rtc.now();
Serial.print(now.year());
Serial.print('/');
print2(now.month());
Serial.print('/');
print2(now.day());
Serial.print(' ');
print2(now.hour());
Serial.print(':');
print2(now.minute());
Serial.print(':');
print2(now.second());
Serial.print(' ');
Serial.println(DAYS[now.dayOfTheWeek()]);
delay(1000);
}
Parts list
2 parts, plus the jumper wires. They retail for about $30; on Mokxi they're free.
How it is wired
4 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Arduino Uno R3 pin 5V; Real-time clock, DS3231 pin VCC
- Ground: Arduino Uno R3 pin GND; Real-time clock, DS3231 pin GND
- Arduino Uno R3 pin A4; Real-time clock, DS3231 pin SDA
- Arduino Uno R3 pin A5; Real-time clock, DS3231 pin SCL
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.