I am developing code to run a word clock and have noticed a slight problem. I am using a DS3231 to keep time, and using the Wire
library to communicate with it. I ping the DS3231 every second to get the time and check a few other things. This is all working fine except when the clock loses power. It seems that occasionally upon loss of power to the Arduino, the time that that the DS3231 reports when it regains power, is incorrect.
My thought is that the power is getting cut in the middle of various Wire.read()
commands and this is causing the chip to mess up and reset its own time, but I am not sure. The DS3231 has a battery backup attached to it, and that battery has only been plugged in for a month or two, so I don't imagine that is the problem.
I am wondering if anyone has an idea how I can deal with this potential problem, or if there is some way I can clear the Wire
library before it starts up again.
I have put some sample code below to give an idea of what I am doing. There is of course much more code, but this is the only relevant part.
#include "Wire.h"
#define kClockAddress 0x68
void readDS3231time(byte * second, byte * minute, byte * hour, byte * dayOfWeek, byte * dayOfMonth, byte * month, byte * year) {
Wire.beginTransmission(kClockAddress);
Wire.write(0); // set DS3231 register pointer to 00h
Wire.endTransmission();
Wire.requestFrom(kClockAddress, 7); // request seven bytes of data from DS3231 starting from register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year) { // sets time and date data to DS3231
Wire.beginTransmission(kClockAddress);
Wire.write(0); // set next input to start at the seconds register
Wire.write(decToBcd(second)); // set seconds
Wire.write(decToBcd(minute)); // set minutes
Wire.write(decToBcd(hour)); // set hours
Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
Wire.write(decToBcd(month)); // set month
Wire.write(decToBcd(year)); // set year (0 to 99)
Wire.endTransmission();
}
void setup() {
// put your setup code here, to run once:
Wire.begin()
// DS3231 seconds, minutes, hours, day, date, month, year
//setDS3231time(0, 36, 10, 2, 21, 12, 15);
}
void loop() {
// put your main code here, to run repeatedly:
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; // retrieve data from DS3231
readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
delay(1000);
}
01/01/00 01 00:00:00
? – Gerben Dec 21 '15 at 19:11