https://github.com/JChristensen/MCP79412RTC
README file
Jack Christensen
May 2025
Arduino MCP79412 RTC Library Copyright (C) 2012-2025 byJack Christensen GNU GPL v3.0
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License v3.0 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/gpl.html
Version 3.0.0 adds the ability to address different I2C peripherals for microcontrollers that have more than one (e.g. Wire, Wire1, etc.) There is one situation that is not backwards compatible with earlier versions of the library. Code that calls setSyncProvider() in the Time library, e.g.:
setSyncProvider(myRTC.get);Needs to change as follows:
setSyncProvider([](){return myRTC.get();});This uses a lambda to provide the Time library with a static function, which it requires. The MCP79412::get() function was static in previous versions of the library, but no longer is in v3.0.0. This allows the flexibility to operate with different I2C peripherals.
The 2.0.0 version of the library has some significant changes and is not completely backwards compatible with earlier versions. These changes provide a more consistent API and reduce the possibility of name collisions. While sketches using this library will likely require changes as a result, these should be mostly straightforward.
- The library no longer defines an
MCP79412RTCobject, therefore each sketch needs to define one. (Previous versions of the library defined anMCP79412RTCobject namedRTC, although only for AVR architecture. Consider using a name other thanRTCas this can cause a name collision on some architectures.) - The constructor no longer has the capability to initialize the I2C bus and no longer accepts an optional parameter. Therefore, the sketch needs to call
MCP79412RTC::begin()in thesetup()function or elsewhere as appropriate. - To reduce the possibility of name collisions, the enumerations as well as register addresses, etc. are now defined in the header file within the
MCP79412RTCclass. Therefore, when using any of these names, it will be necessary to include theMCP79412RTCscope, e.g.myRTC.alarm(MCP79412RTC::ALARM_1); - The example sketches and documentation have been updated to reflect these changes.
MCP79412RTC is an Arduino library that supports the Microchip MCP7941x Real-Time Clock/Calendar chips. This library is intended to be used with PJRC's Arduino Time library.
For more information on the MCP79412, see:
The Microchip MCP79412 Product Page for specs, datasheet, etc.
My Blog Post, summarizing the features and advantages of the MCP79412
My Power Outage Logger Project, an Arduino-based project featuring the MCP79412
The following example sketches are included with the MCP79412RTC library:
- rtcSet1: Set the RTC date and time using a hard-coded value in the sketch.
- rtcSet2: Similar to rtcSet1, a different way to hard-code the date and time.
- rtcSet3: Set the RTC to the sketch compile date and time.
- rtc_wire1: Raspberry Pi Pico example using
Wire1. - SetSerial: Set the RTC's date, time, and calibration register from the Arduino serial monitor.
- TimeRTC: Similar to the example of the same name provided with the Time library.
- rtc_interrupt: Uses a 1Hz interrupt from the RTC to keep time.
- PowerOutageLogger: A comprehensive example that implements a power failure logger using the MCP79412's ability to capture power down and power up times. Power failure events are logged to the MCP79412's SRAM. Output is to the Arduino serial monitor.
- tiny79412_KnockBang: Demonstrates interfacing an ATtiny45/85 to the MCP79412.
Symbolic names used with the enableAlarm() function described below.
- ALM_MATCH_SECONDS -- Triggers alarm when the seconds in the RTC time keeping register match the seconds in the alarm register.
- ALM_MATCH_MINUTES -- Triggers when RTC time minutes match alarm minutes.
- ALM_MATCH_HOURS -- Triggers when RTC time hours match alarm hours.
- ALM_MATCH_DAY -- Triggers when day of the week matches. (Triggers at midnight.)
- ALM_MATCH_DATE -- Triggers when date matches. (Triggers at midnight.)
- ALM_MATCH_DATETIME -- Triggers when seconds, minutes, hours, day of week, date and month all match.
- ALM_DISABLE -- Disables the alarm.
Symbolic names used with alarm functions.
- ALARM_0
- ALARM_1
Symbolic names used with the squareWave() function (described below).
- SQWAVE_1_HZ,
- SQWAVE_4096_HZ,
- SQWAVE_8192_HZ,
- SQWAVE_32768_HZ,
- SQWAVE_NONE
Instantiates an MCP79412RTC object.
MCP79412RTC myRTC(wire);
wire: An optional parameter to specify which I2C bus to use. If omitted, defaults to Wire. (TwoWire&)
None.
MCP79412RTC myRTC; // to use Wire
// or
MCP79412RTC myRTC(Wire1); // to use Wire1
Initializes the I2C bus. Calls Wire.begin().
begin();
None.
None.
MCP79412RTC myRTC;
void setup() {
myRTC.begin();
}Reads the current date and time from the RTC and returns it as a time_t value. Returns zero if an I2C error occurs (RTC not present, etc.).
RTC.get();
None.
Current date and time (time_t)
time_t myTime;
myTime = RTC.get();Sets the RTC date and time to the given time_t value.
RTC.set(t);
t: The date and time to set the RTC to (time_t)
None.
//this example first sets the system time (maintained by the Time library) to
//a hard-coded date and time, and then sets the RTC from the system time.
//the setTime() function is part of the Time library.
setTime(23, 31, 30, 13, 2, 2009); //set the system time to 23h31m30s on 13Feb2009
RTC.set(now()); //set the RTC from the system timeReads the current date and time from the RTC and returns it as a tmElements_t structure. Returns false if an I2C error occurs (RTC not present, etc.). See the Arduino Time library for details on the tmElements_t structure.
RTC.read(tm);
tm: Address of a tmElements_t structure to which the date and time are returned.
False if an I2C error occurred, else true. The date and time read from the RTC are returned to the tm parameter.
tmElements_t tm;
RTC.read(tm);
Serial.print(tm.Hour, DEC);
Serial.print(':');
Serial.print(tm.Minute,DEC);
Serial.print(':');
Serial.println(tm.Second,DEC);Sets the RTC to the date and time given by a tmElements_t structure.
RTC.write(tm);
tm: Address of a tmElements_t structure used to set the date and time.
None.
tmElements_t tm;
tm.Hour = 23; //set the tm structure to 23h31m30s on 13Feb2009
tm.Minute = 31;
tm.Minute = 30;
tm.Day = 13;
tm.Month = 2;
tm.Year = 2009 - 1970; //tmElements_t.Year is the offset from 1970
RTC.write(tm); //set the RTC from the tm structureReturns a boolean value indicating whether the RTC's oscillator is running. When there is no backup battery present, the RTC will reset when it is next powered up, and the oscillator will not be running. Setting the time with RTC.set() or RTC.write() starts the oscillator.
RTC.isRunning();
None.
True if the RTC's oscillator is running, else false (boolean)
if ( RTC.isRunning() )
//do something
else
//do something elseThe MCP79412 RTC has two alarms (Alarm-0 and Alarm-1) that can be used separately or simultaneously. When an alarm is triggered, a flag is set in the RTC that can be detected with the alarm() function below. Optionally, the RTC's Multi-Function Pin (MFP) can be driven to either a low or high logic level when an alarm is triggered. When using the MFP with both alarms, be sure to read the comments on the alarmPolarity() function below.
Sets an alarm date and time. This sets the alarm registers only, it does not enable the alarm, this is done using the enableAlarm() function. alarmNumber is 0 or 1, but is ruthlessly masked to ensure a valid value. Note that depending on the alarm type chosen (see enableAlarm() below), only selected date or time parts may act as alarm critera. Nevertheless, valid values should be specified in the alarmTime parameter.
RTC.setAlarm(alarmNumber, alarmTime);
alarmNumber: ALARM_0 or ALARM_1 (byte)
alarmTime: Date and time to set the alarm to (time_t)
None.
//set alarm-1 for 30 seconds after midnight on 21Dec2012
tmElements_t tm;
tm.Hour = 0;
tm.Minute = 0;
tm.Second = 30;
tm.Year = CalendarYrToTm(2012);
tm.Month = 12;
tm.Day = 21;
RTC.setAlarm(ALARM_1, makeTime(tm));Enable or disable the given alarm.
RTC.enableAlarm(alarmNumber, alarmType);
alarmNumber: ALARM_0 or ALARM_1 (byte)
alarmType: One of the following: ALM_MATCH_SECONDS, ALM_MATCH_MINUTES, ALM_MATCH_HOURS, ALM_MATCH_DAY, ALM_MATCH_DATE, ALM_MATCH_DATETIME, ALM_DISABLE. (ALM_MATCH_DATETIME triggers the alarm when seconds, minutes, hours, day, date and month all match.)
None.
//disable alarm-0
RTC.enableAlarm(ALARM_0, ALM_DISABLE);
//enable alarm-1 to trigger when the minutes match.
//assuming alarm-1 is set as in the example above, this will trigger the
//alarm every hour, on the hour (minutes=0).
RTC.enableAlarm(ALARM_1, ALM_MATCH_MINUTES);
//enable alarm-1 to trigger when the seconds match.
//assuming alarm-1 is set as in the example above, this will trigger the
//alarm once a minute, at 30 seconds past the minute.
RTC.enableAlarm(ALARM_1, ALM_MATCH_SECONDS);Tests whether the given alarm has been triggered, and returns a corresponding boolean value. Clears the alarm flag to ensure that the next trigger event can be trapped.
RTC.alarm(byte alarmNumber);
alarmNumber: ALARM_0 or ALARM_1 (byte)
True if the alarm was triggered, else false (boolean)
if ( RTC.alarm(ALARM_0) )
//alarm-0 has triggered
else
//alarm-0 has not triggeredSpecifies the logic level on the Multi-Function Pin (MFP) when an alarm is triggered. The default is LOW. When both alarms are active, the two are ORed together to determine the level of the MFP. With alarm polarity set to LOW (the default), this causes the MFP to go low only when BOTH alarms are triggered. With alarm polarity set to HIGH, the MFP will go high when EITHER alarm is triggered. Note that the state of the MFP is independent of the RTC's (so-called) alarm "interrupt" flags, and that the alarm() function will indicate when an alarm is triggered regardless of the polarity.
RTC.alarmPolarity(boolean polarity);
polarity: HIGH or LOW (boolean)
None.
RTC.alarmPolarity(HIGH); //drives MFP high when an alarm is triggeredThe MCP79412 RTC has 64 bytes of battery-backed SRAM that can be read and written with the following functions using addresses between 0 and 63. Addresses passed to these functions are constrained to the valid range by an AND function.
Writes a single byte to the SRAM.
RTC.sramWrite(addr, value);
addr: SRAM address to write (byte)
value: Value to write (byte)
None.
RTC.sramWrite(3, 14); //write the value 14 to SRAM address 3Writes multiple bytes to consecutive SRAM locations. nBytes must be between 1 and 31. Invalid values of nBytes, or combinations of addr and nBytes that would result in addressing past the last byte of SRAM will result in no action.
RTC.sramWrite(addr, values, nBytes);
addr: First SRAM address to write (byte)
value: An array of values to write (*byte)
nBytes: Number of bytes to write (byte)
None.
//write 1, 2, ..., 8 to the first eight SRAM locations
byte buf[8] = {1, 2, 3, 4, 5, 6, 7, 8};
RTC.sramWrite(0, buf, 8);Reads a single byte from SRAM.
RTC.sramRead(addr);
addr: SRAM address to read (byte)
The value read (byte)
byte val;
val = RTC.sramRead(3); //read the value from SRAM location 3Reads multiple bytes from consecutive SRAM locations. nBytes must be between 1 and 32. Invalid values of nBytes, or combinations of addr and nBytes that would result in addressing past the last byte of SRAM will result in no action.
RTC.sramRead(addr, values, nBytes);
addr: First SRAM address to read (byte)
values: An array to receive the read values (*byte)
nBytes: Number of bytes to read (byte)
No function value returned. Bytes read from SRAM are returned to the values array.
//read the last eight locations of SRAM into buf
byte buf[8];
RTC.sramRead(56, buf, 8);The MCP79412 RTC has 128 bytes of non-volatile EEPROM that can be read and written with the following functions using addresses between 0 and 127. Addresses passed to these functions are constrained to the valid range by an AND function.
EEPROM is paged memory with a page size of 8 bytes; when writing multiple bytes, this this limits the number of bytes that can be written at one time to 8. Page writes must start on a page boundary.
Writes a single byte to EEPROM.
RTC.eepromWrite(addr, value);
addr: EEPROM address to write (byte)
value: Value to write (byte)
None.
RTC.eepromWrite(42, 55); //write the value 55 to EEPROM address 42Writes a page (8 bytes) or less to EEPROM. addr should be a page start address (0, 8, ..., 120), but if not, is ruthlessly coerced into a valid value with an AND function. nBytes must be between 1 and 8, other values result in no action.
RTC.eepromWrite(addr, values, nBytes);
addr: First EEPROM address to write (byte)
value: An array of values to write (*byte)
nBytes: Number of bytes to write (byte)
None.
//write 1, 2, ..., 8 to the first eight EEPROM locations
byte buf[8] = {1, 2, 3, 4, 5, 6, 7, 8};
RTC.eepromWrite(0, buf, 8);Reads a single byte from EEPROM and returns the value.
RTC.eepromRead(byte addr);
addr: EEPROM address to read (byte)
The value read (byte)
byte val;
val = RTC.eepromRead(42); //read the value from EEPROM location 42Reads multiple bytes from consecutive EEPROM locations. nBytes must be between 1 and 32. Invalid values of nBytes, or combinations of addr and nBytes that would result in addressing past the last byte of EEPROM will result in no action.
RTC.eepromRead(addr, values, nBytes);
addr: First EEPROM address to read (byte)
values: An array to receive the read values (*byte)
nBytes: Number of bytes to read (byte)
No function value returned. The bytes read from EEPROM are returned to the values array.
//read the last eight locations of EEPROM into buf
byte buf[8];
RTC.eepromRead(120, buf, 8);Writes the given value to the RTC calibration register. This is an adjustment factor in PPM (approximately), and must be between -127 and 127. Negative numbers cause the RTC to run faster, positive numbers cause it to run slower.
RTC.calibWrite(int value);
value: The calibration value to set, between -127 and 127 (int)
None.
RTC.calibWrite(13); //makes the RTC run slower by 13 parts per million.
RTC.calibWrite(-42); //makes the RTC run faster by 42 parts per million.Reads the RTC calibration register.
RTC.calibRead();
None.
RTC calibration register value (int)
int value;
value = RTC.calibRead();Returns a boolean value (true or false) to indicate whether a power failure has occurred. If a power failure occurred, the power down and power up timestamps are returned in the variables given by the caller, the RTC's power fail flag is reset and the power up/down timestamps are cleared.
Note that the power down and power up timestamp registers do not contain values for seconds or for the year. The returned time stamps will therefore contain the current year from the RTC. However, there is the possibility that a power outage spans from one year to the next. If this occurs, the power down timestamp would appear to be at a later time than the power up timestamp; if this is encountered, powerFail() will subtract one year from the power down timestamp before returning it.
Still, there is an assumption that the timestamps are being read in the same year as that when the power up occurred. If this is not the case the year in the returned timestamp will be invalid.
Finally, note that once the RTC records a power outage, it must be cleared before another can be recorded. If two power outages occur before powerFail() is called again, the time stamps for the earlier outage will be returned and the timestamps for the second outage will be lost.
RTC.powerFail(powerDown, powerUp);
powerDown: Pointer to a time_t variable to hold the returned power down timestamp.
powerUp: Pointer to a time_t variable to hold the returned power up timestamp.
True if a power failure occurred, else false (boolean)
time_t powerDown, powerUp; //power outage timestamps
if ( RTC.powerFail(&powerDown, &powerUp) ) {
//do something
else
//do something elseEnables or disables the square wave output on the multi-function pin (MFP).
RTC.squareWave(byte freq);
freq: One of the following: SQWAVE_1_HZ, SQWAVE_4096_HZ, SQWAVE_8192_HZ, SQWAVE_32768_HZ, SQWAVE_NONE (byte)
None.
RTC.squareWave(SQWAVE_1_HZ); //output a 1Hz square wave on the MFPSets the logic level on the MFP when it's not being used as a square wave or alarm output. The default value after the RTC chip is reset is HIGH.
RTC.out(boolean level);
level: HIGH or LOW (boolean)
None.
RTC.out(LOW); //set the MFP to a low logic levelReads the 64-bit unique ID from the RTC.
RTC.idRead(byte *uniqueID);
uniqueID: An 8-byte array to receive the unique ID (*byte)
No function value returned. The RTC's ID is returned to the uniqueID array.
byte buf[8];
RTC.idRead(buf);Set or clear the VBATEN bit. Setting the bit powers the clock and SRAM from the backup battery when Vcc falls. Note that setting the time via set() or write() sets the VBATEN bit.
RTC.vbaten(boolean enable);
enable: true or false (boolean)
None.
RTC.vbaten(false);Returns an EUI-64 ID. For an MCP79412, calling this function is equivalent to calling idRead(). For an MCP79411, the EUI-48 ID is converted to EUI-64. Caller must provide an 8-byte array to contain the results.
RTC.getEUI64(byte *uniqueID);
uniqueID: An 8-byte array to receive the EUI-64 unique ID (*byte)
No function value returned. The EUI-64 ID is returned to the uniqueID array.
byte buf[8];
RTC.getEUI64(buf);