Re: Mains powered clock
For anyone who wants to test the DS3231 RTC battery automatically - this is my empirical RTC power down/up sequence. Will probably work with other low power I2C RTC modules too. My I2C chain also happily supports a 16 port expander.
The DS3231 RTC is powered from a digital port as it only needs a few milliamps.
The RTC CR2032 battery + probe is connected via a reed relay to an analogue port - which has a 1M resistor to ground to drain any residual voltage.
The Arduino Nano/Uno I2C SDA and SCL digital shadow ports A4, A5 are initially declared as INPUT.
The I2C interface can lock up the processor if this druidic ritual is not followed.
//
pinMode(A5, OUTPUT);
pinMode(A4, OUTPUT);
// force SDA and SCL low via their digital shadow ports on UNO and NANO
digitalWrite(A5, LOW);
digitalWrite(A4, LOW);
delay(2000);
//
digitalWrite(RTCPowerPin, LOW);
Serial.println(F("Removing RTC power"));
delay(5000);
//
digitalWrite(RTCBatteryTestRelayPin,HIGH);
delay(100);
BatteryVoltage = ((float)(analogRead(RTCBatteryTestVoltagePin)*5))/1024;
digitalWrite(RTCBatteryTestRelayPin,LOW);
//
digitalWrite(RTCPowerPin, HIGH);
//
delay(2000);
pinMode(A5, INPUT);
pinMode(A4, INPUT);
//
delay(2000);
// I2C needs reinitialising else hangs
//!! a commonly recommended TWCR value of 0 causes crashes
TWCR=0x94; // stop
//
// Initialize the rtc object
rtc.begin();