Skip to content

Real Time Clock (RTC) DS3231

The real-time clock is connected with the I2C lines of the ATmega328p. The RTC keeps information about seconds, minutes, hours, day, date, month and year.But this chip can also measure temperature with a ±3°C accuracy.

Setting up DS3231 in arduino project

To be able to work with the DS3231 in your arduino project you need to include the following libraries:

Wire.h
Sodaq_DS3231.h

The code to run in the arduino setup function:

Wire.begin();  
rtc.begin();

Now you are ready to start using the DS3231 in your code.

Reading time from the DS3231

To be able to get data from the RTC you have to something like this:

now = rtc.now();
uint32_t ts = now.getEpoch();

The epoch timestamp is a 4bits timestamp. But that isn’t the only thing you can get from it, you are also able to ask each separate item with its own function:

 char weekDay[][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
 Serial.print(now.year(), DEC);
 Serial.print('/');
 Serial.print(now.month(), DEC);
 Serial.print('/');
 Serial.print(now.date(), DEC);
 Serial.print(' ');
 Serial.print(now.hour(), DEC);
 Serial.print(':');
 Serial.print(now.minute(), DEC);
 Serial.print(':');
 Serial.print(now.second(), DEC);
 Serial.print(' ');
 Serial.print(weekDay[now.dayOfWeek());
 ```

 Here is a function that is handy to be able to set up the RTC

 ``` Arduino
 void adjustDate(int year, int month, int date, int hour, int min, int sec, int weekday){
DateTime dt(year, month, date, hour, min, sec, weekday);
rtc.setDateTime(dt); //Adjust date-time as defined 'dt' above 
//Serial.println(rtc.now().getEpoch());//debug info
}

Reading from the temp sensor

To read data from the temp sensor you need to use the following code:

rtc.convertTemperature();            //convert current temperature into registers
float tempFloat = rtc.getTemperature(); //read registers and display the temperature
Back to top