From 2b4d667295da1289da09950dc67fa744160da66f Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 7 Apr 2018 16:31:43 -0400 Subject: [PATCH 01/22] README case conflict. --- ReadMe.md => README (Case Conflict).md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ReadMe.md => README (Case Conflict).md (100%) diff --git a/ReadMe.md b/README (Case Conflict).md similarity index 100% rename from ReadMe.md rename to README (Case Conflict).md From af4b93e4e04790066868010858265af279177de5 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 7 Apr 2018 16:37:33 -0400 Subject: [PATCH 02/22] Rename README. --- README (Case Conflict).md => README.md | 0 ReadMe.txt | 342 ------------------------- 2 files changed, 342 deletions(-) rename README (Case Conflict).md => README.md (100%) delete mode 100644 ReadMe.txt diff --git a/README (Case Conflict).md b/README.md similarity index 100% rename from README (Case Conflict).md rename to README.md diff --git a/ReadMe.txt b/ReadMe.txt deleted file mode 100644 index a5dd0f1..0000000 --- a/ReadMe.txt +++ /dev/null @@ -1,342 +0,0 @@ -ReadMe file for Arduino MCP79412 Library v1.0 -https://github.com/JChristensen/MCP79412RTC -Jack Christensen Sep 2012 - -This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 -Unported License. To view a copy of this license, visit -http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative -Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. - -================================================================================ -Arduino library to support the Microchip MCP79412 Real-Time Clock. This library -is intended for use with the Arduino Time.h library, -http://www.arduino.cc/playground/Code/Time. - -The MCP79412 library is a drop-in replacement for the DS1307RTC.h library by -Michael Margolis that is supplied with the Arduino Time library above. To change -from using a DS1307 RTC to an MCP79412 RTC, it is only necessary to change the -#include statement to include MCP79412RTC.h instead of DS1307RTC.h. - -This library also implements methods to support the additional features -of the MCP79412. - --------------------------------------------------------------------------------- -To use the library: -(1) Go to https://github.com/JChristensen/MCP79412RTC and click the -Download ZIP button and save the ZIP file to a convenient location on your PC. -(2) Uncompress the downloaded file. This will result in a folder containing -the library files, which has a name that includes the branch name, -e.g. MCP79412-master. -(3) Rename the folder to just "MCP79412". -(4) Move the renamed folder to the Arduino sketchbook\libraries folder. - --------------------------------------------------------------------------------- -The following example sketches are included with the Timezone 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. - -SetSerial: Set the RTC's date, time, and calibration register from -Arduino serial monitor. - -rtcSetSerial: Set the RTC via serial input from the Arduino serial monitor. - -TimeRTC: Same as the example of the same name provided with the Time library, -demonstrating the interchangeability of the MCP79412RTC library with the -DS1307RTC library. - -PowerOutageLogger: A comprehensive example that implements a power failure -logger using the MCP79412RTC's ability to capture power down and power up times. -Power failure events are logged to the MCP79412RTC's SRAM. Output is to the -Arduino serial monitor. - -tiny79412_KnockBang: Demonstrates interfacing an ATtiny45/85 to the -MCP79412. - --------------------------------------------------------------------------------- -Similar to the DS1307RTC library, the MCP79412 library instantiates an RTC -object; the user does not need to do this. - -To use the MCP79412 library, the Time and Wire libraries must also be included. -For brevity, these includes are not repeated in the examples below: -#include //http://github.com/JChristensen/MCP79412RTC -#include //http://www.arduino.cc/playground/Code/Time -#include //http://arduino.cc/en/Reference/Wire - //(Wire.h is included with Arduino IDE) - -================================================================================ -SETTING AND READING THE TIME - --------------------------------------------------------------------------------- -The get() method reads the current time from the RTC and returns it as a time_t -value. - - time_t myTime; - myTime = RTC.get(); - --------------------------------------------------------------------------------- -The set(time_t t) method sets the RTC to the given time_t value. -The example below first sets the system time (maintained by the Time library) to -a hard-coded date and time, then sets the RTC from the system time. The -setTime(hr, min, sec, day, month, year) function comes from the Time library. - - setTime(23, 31, 30, 13, 2, 2009); //set the system time to - //23h31m30s on 3Feb2009 - RTC.set(now()); //set the RTC from the system time - --------------------------------------------------------------------------------- -The read(tmElements_t &tm) method reads the current time from the RTC and -returns it as a tmElements_t structure. -(See the Arduino Time library for details on the tmElements_t structure: -http://www.arduino.cc/playground/Code/Time.) - - 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); - --------------------------------------------------------------------------------- -The write(tmElements_t &tm) method sets the RTC to the date and time -as represented in a tmElements_t structure. - - 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 structure - --------------------------------------------------------------------------------- -The isRunning() method returns a boolean value (true or false) 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 starts the oscillator. - - if ( RTC.isRunning() ) - //do something - else - //do something else - -================================================================================ -READING AND WRITING STATIC RAM (SRAM) - -The MCP79412 RTC has 64 bytes of battery-backed SRAM that can be read and -written with the following methods using addresses between 0 and 63. Addresses -passed to these functions are constrained to the valid range by an AND function. - --------------------------------------------------------------------------------- -sramWrite(byte addr, byte value) writes a single byte to the SRAM. - - RTC.sramWrite(3, 14); //write the value 14 to SRAM address 3 - --------------------------------------------------------------------------------- -sramWrite(byte addr, byte *values, byte nBytes) writes 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. - - //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); - --------------------------------------------------------------------------------- -sramRead(byte addr) reads a single byte from SRAM and returns the value. - - byte val; - val = RTC.sramRead(3); //read the value from SRAM location 3 - --------------------------------------------------------------------------------- -sramRead(byte addr, byte *values, byte nBytes) reads 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. - - //read the last eight locations of SRAM into buf - byte buf[8]; - RTC.sramRead(56, buf, 8); - -================================================================================ -READING AND WRITING EEPROM - -The MCP79412 RTC has 128 bytes of non-volatile EEPROM that can be read and -written with the following methods 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 to 8. Page writes must -start on a page boundary. - --------------------------------------------------------------------------------- -eepromWrite(byte addr, byte value) writes a single byte to EEPROM. - - RTC.eepromWrite(42, 55); //write the value 55 to EEPROM address 42 - --------------------------------------------------------------------------------- -eepromWrite(byte addr, byte *values, byte nBytes) writes 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. - - //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); - --------------------------------------------------------------------------------- -eepromRead(byte addr) reads a single byte from EEPROM and returns the value. - - byte val; - val = RTC.eepromRead(42); //read the value from EEPROM location 42 - --------------------------------------------------------------------------------- -eepromRead(byte addr, byte *values, byte nBytes) reads 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. - - //read the last eight locations of EEPROM into buf - byte buf[8]; - RTC.eepromRead(120, buf, 8); - -================================================================================ -ALARM FUNCTIONS - -The 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. - --------------------------------------------------------------------------------- -setAlarm(uint8_t alarmNumber, time_t alarmTime) 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. - - //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)); - --------------------------------------------------------------------------------- -enableAlarm(uint8_t alarmNumber, uint8_t alarmType) enable or disable the given -alarm (0 or 1). alarmNumber is masked to ensure a value of 0 or 1. alarmType is -one of the following: ALM_MATCH_SECONDS, ALM_MATCH_MINUTES, ALM_MATCH_HOURS, -ALM_MATCH_DAY, ALM_MATCH_DATE, ALM_MATCH_DATETIME, ALM_DISABLE. - - //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); - --------------------------------------------------------------------------------- -alarm(uint8_t alarmNumber) tests whether the given alarm (0 or 1) has been -triggered, and returns a corresponding boolean value (true or false). Clears the -alarm flag to ensure that the next trigger event can be trapped. - - if ( RTC.alarm(ALARM_0) ) - //alarm-0 has triggered - else - //alarm-0 has not triggered - --------------------------------------------------------------------------------- -alarmPolarity(boolean polarity) specifies 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 -alarm "interrupt" flags, and the alarm() function will indicate when an alarm is -triggered regardless of the polarity. - - RTC.alarmPolarity(HIGH); //drives MFP high when an alarm is triggered - -================================================================================ -CALIBRATION, POWER FAILURE DETECTION, AND MISCELLANEOUS FUNCTIONS - --------------------------------------------------------------------------------- -calibWrite(int value) writes the given value to the RTC calibration register. -This is an adjustment factor in PPM, and must be between -127 and 127. Negative -numbers cause the RTC to run faster, positive numbers cause it to run slower. - - 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. - --------------------------------------------------------------------------------- -calibRead(void) returns the value of the RTC calibration register. - - int value; - value = RTC.calibRead(); - --------------------------------------------------------------------------------- -powerFail(time_t *powerDown, time_t *powerUp) returns a boolean value (true or -false) to indicate whether a power failure has occurred. If one 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 a chance 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. - -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. - - time_t powerDown, powerUp; //power outage timestamps - if ( RTC.powerFail(&powerDown, &powerUp) ) { - //do something - else - //do something else - --------------------------------------------------------------------------------- -squareWave(uint8_t freq) enables or disables the square wave output on the -multi-function pin (MFP). freq is one of the following: SQWAVE_1_HZ, -SQWAVE_4096_HZ, SQWAVE_8192_HZ, SQWAVE_32768_HZ, SQWAVE_NONE - - RTC.squareWave(SQWAVE_1_HZ); //output a 1Hz square wave on the MFP - --------------------------------------------------------------------------------- -out(boolean level) sets the logic level on the MFP when it's not being used as a -square wave or alarm output. The default value after an RTC chip reset is HIGH. - - RTC.out(LOW); //set the MFP to a low logic level - --------------------------------------------------------------------------------- -idRead(byte *uniqueID) returns the 64-bit unique ID from the RTC into the given -8-byte array. - - byte buf[8]; - RTC.idRead(buf); - From e3a8d01bcc8e3418645eb3facb95c29319a2bc9d Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 7 Apr 2018 16:41:55 -0400 Subject: [PATCH 03/22] Fix markup in README file. Move source files to src directory. --- README.md | 321 +++++++++++++------------ MCP79412RTC.cpp => src/MCP79412RTC.cpp | 0 MCP79412RTC.h => src/MCP79412RTC.h | 0 3 files changed, 161 insertions(+), 160 deletions(-) rename MCP79412RTC.cpp => src/MCP79412RTC.cpp (100%) rename MCP79412RTC.h => src/MCP79412RTC.h (100%) diff --git a/README.md b/README.md index 950a12c..7b7eeca 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ # Arduino MCP79412 RTC Library v1.0 # https://github.com/JChristensen/MCP79412RTC ReadMe file -Jack Christensen Sep 2012 +Jack Christensen +Sep-2012 ![CC BY-SA](http://mirrors.creativecommons.org/presskit/buttons/80x15/png/by-sa.png) -## Introduction ## +## Introduction **MCP79412RTC** is an Arduino library that supports the Microchip MCP7941x Real-Time Clock/Calendar chips. It is intended to be used with the [Arduino Time library] (http://www.arduino.cc/playground/Code/Time). The **MCP79412RTC** library is a drop-in replacement for the **DS1307RTC** library by Michael Margolis that is supplied with the [Arduino Time library](http://www.arduino.cc/playground/Code/Time). To change from using a DS1307 RTC to an MCP7941x RTC, it is only necessary to use `#include ` instead of `#include `. @@ -18,14 +19,14 @@ The **MCP79412RTC** library also implements methods to support the additional fe The [Microchip MCP79412 Product Page](http://goo.gl/SHfKe0) for specs, datasheet, etc. MCP79411 and MCP79412 breakout boards are available at [my Tindie Store](http://goo.gl/UzAVcZ) -## Installation ## +## Installation To use the **MCP79412RTC** library: - Go to https://github.com/JChristensen/MCP79412RTC, click the **Download ZIP** button and save the ZIP file to a convenient location on your PC. - Uncompress the downloaded file. This will result in a folder containing all the files for the library, that has a name that includes the branch name, usually **MCP79412RTC-master**. - Rename the folder to just **MCP79412RTC**. - Copy the renamed folder to the Arduino sketchbook\libraries folder. -## Examples ## +## Examples 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. @@ -36,7 +37,7 @@ The following example sketches are included with the **MCP79412RTC** library: - **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. -## Usage notes ## +## Usage notes Similar to the **DS1307RTC** library, the **MCP79412RTC** library instantiates an RTC object; the user does not need to do this. To use the **MCP79412RTC** library, the Time and Wire libraries must also be included. For brevity, these includes are not repeated in the examples below: @@ -46,33 +47,33 @@ To use the **MCP79412RTC** library, the Time and Wire libraries must also be inc #include //http://arduino.cc/en/Reference/Wire (included with Arduino IDE) ``` -## Methods for setting and reading the time ## +## Methods for setting and reading the time -###get(void) -#####Description +### get(void) +##### Description 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.). -#####Syntax +##### Syntax `RTC.get();` -#####Parameters +##### Parameters None. -#####Returns +##### Returns Current date and time *(time_t)* -#####Example +##### Example ```c++ time_t myTime; myTime = RTC.get(); ``` -###set(time_t t) -#####Description +### set(time_t t) +##### Description Sets the RTC date and time to the given *time_t* value. -#####Syntax +##### Syntax `RTC.set(t);` -#####Parameters +##### Parameters **t:** The date and time to set the RTC to *(time_t)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ //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. @@ -81,16 +82,16 @@ setTime(23, 31, 30, 13, 2, 2009); //set the system time to 23h31m30s on 13Feb2 RTC.set(now()); //set the RTC from the system time ``` -###read(tmElements_t &tm) -#####Description +### read(tmElements_t &tm) +##### Description Reads 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](http://www.arduino.cc/playground/Code/Time) for details on the *tmElements_t* structure. -#####Syntax +##### Syntax `RTC.read(tm);` -#####Parameters +##### Parameters **tm:** Address of a *tmElements_t* structure to which the date and time are returned. -#####Returns +##### Returns False if an I2C error occurred, else true. The date and time read from the RTC are returned to the **tm** parameter. -#####Example +##### Example ```c++ tmElements_t tm; RTC.read(tm); @@ -101,16 +102,16 @@ Serial.print(':'); Serial.println(tm.Second,DEC); ``` -###write(tmElements_t &tm) -#####Description +### write(tmElements_t &tm) +##### Description Sets the RTC to the date and time given by a *tmElements_t* structure. -#####Syntax +##### Syntax `RTC.write(tm);` -#####Parameters +##### Parameters **tm:** Address of a *tmElements_t* structure used to set the date and time. -#####Returns +##### Returns None. -#####Example +##### Example ```c++ tmElements_t tm; tm.Hour = 23; //set the tm structure to 23h31m30s on 13Feb2009 @@ -122,16 +123,16 @@ tm.Year = 2009 - 1970; //tmElements_t.Year is the offset from 1970 RTC.write(tm); //set the RTC from the tm structure ``` -###isRunning(void) -#####Description +### isRunning(void) +##### Description Returns 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. -#####Syntax +##### Syntax `RTC.isRunning();` -#####Parameters +##### Parameters None. -#####Returns +##### Returns True if the RTC's oscillator is running, else false *(boolean)* -#####Example +##### Example ```c++ if ( RTC.isRunning() ) //do something @@ -139,160 +140,160 @@ else //do something else ``` -## Methods for reading and writing static RAM (SRAM) ## +## Methods for reading and writing static RAM (SRAM) The MCP79412 RTC has 64 bytes of battery-backed SRAM that can be read and written with the following methods using addresses between 0 and 63. Addresses passed to these functions are constrained to the valid range by an AND function. -###sramWrite(byte addr, byte value) -#####Description +### sramWrite(byte addr, byte value) +##### Description Writes a single byte to the SRAM. -#####Syntax +##### Syntax `RTC.sramWrite(addr, value);` -#####Parameters +##### Parameters **addr:** SRAM address to write *(byte)* **value:** Value to write *(byte)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ RTC.sramWrite(3, 14); //write the value 14 to SRAM address 3 ``` -###sramWrite(byte addr, byte *values, byte nBytes) -#####Description +### sramWrite(byte addr, byte *values, byte nBytes) +##### Description Writes 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. -#####Syntax +##### Syntax `RTC.sramWrite(addr, values, nBytes);` -#####Parameters +##### Parameters **addr:** First SRAM address to write *(byte)* **value:** An array of values to write _(*byte)_ **nBytes:** Number of bytes to write *(byte)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ //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); ``` -###sramRead(byte addr) -#####Description +### sramRead(byte addr) +##### Description Reads a single byte from SRAM. -#####Syntax +##### Syntax `RTC.sramRead(addr);` -#####Parameters +##### Parameters **addr:** SRAM address to read *(byte)* -#####Returns +##### Returns The value read *(byte)* -#####Example +##### Example ```c++ byte val; val = RTC.sramRead(3); //read the value from SRAM location 3 ``` -###sramRead(byte addr, byte *values, byte nBytes) -#####Description +### sramRead(byte addr, byte *values, byte nBytes) +##### Description Reads 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. -#####Syntax +##### Syntax `RTC.sramRead(addr, values, nBytes);` -#####Parameters +##### Parameters **addr:** First SRAM address to read *(byte)* **values:** An array to receive the read values _(*byte)_ **nBytes:** Number of bytes to read *(byte)* -#####Returns +##### Returns No function value returned. Bytes read from SRAM are returned to the **values** array. -#####Example +##### Example ```c++ //read the last eight locations of SRAM into buf byte buf[8]; RTC.sramRead(56, buf, 8); ``` -## Methods for Reading and writing EEPROM ## +## Methods for Reading and writing EEPROM The MCP79412 RTC has 128 bytes of non-volatile EEPROM that can be read and written with the following methods 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. -###eepromWrite(byte addr, byte value) -#####Description +### eepromWrite(byte addr, byte value) +##### Description Writes a single byte to EEPROM. -#####Syntax +##### Syntax `RTC.eepromWrite(addr, value);` -#####Parameters +##### Parameters **addr:** EEPROM address to write *(byte)* **value:** Value to write *(byte)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ RTC.eepromWrite(42, 55); //write the value 55 to EEPROM address 42 ``` -###eepromWrite(byte addr, byte *values, byte nBytes) -#####Description +### eepromWrite(byte addr, byte *values, byte nBytes) +##### Description Writes 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. -#####Syntax +##### Syntax `RTC.eepromWrite(addr, values, nBytes);` -#####Parameters +##### Parameters **addr:** First EEPROM address to write *(byte)* **value:** An array of values to write _(*byte)_ **nBytes:** Number of bytes to write *(byte)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ //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); ``` -###eepromRead(byte addr) -#####Description +### eepromRead(byte addr) +##### Description Reads a single byte from EEPROM and returns the value. -#####Syntax +##### Syntax `RTC.eepromRead(byte addr);` -#####Parameters +##### Parameters **addr:** EEPROM address to read *(byte)* -#####Returns +##### Returns The value read *(byte)* -#####Example +##### Example ```c++ byte val; val = RTC.eepromRead(42); //read the value from EEPROM location 42 ``` -###eepromRead(byte addr, byte *values, byte nBytes) -#####Description +### eepromRead(byte addr, byte *values, byte nBytes) +##### Description Reads 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. -#####Syntax +##### Syntax `RTC.eepromRead(addr, values, nBytes);` -#####Parameters +##### Parameters **addr:** First EEPROM address to read *(byte)* **values:** An array to receive the read values _(*byte)_ **nBytes:** Number of bytes to read *(byte)* -#####Returns +##### Returns No function value returned. The bytes read from EEPROM are returned to the **values** array. -#####Example +##### Example ```c++ //read the last eight locations of EEPROM into buf byte buf[8]; RTC.eepromRead(120, buf, 8); ``` -## Alarm methods ## +## Alarm methods The 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. -###setAlarm(byte alarmNumber, time_t alarmTime) -#####Description +### setAlarm(byte alarmNumber, time_t alarmTime) +##### Description 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. -#####Syntax +##### Syntax `RTC.setAlarm(alarmNumber, alarmTime);` -#####Parameters +##### Parameters **alarmNumber:** ALARM_0 or ALARM_1 *(byte)* **alarmTime:** Date and time to set the alarm to *(time_t)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ //set alarm-1 for 30 seconds after midnight on 21Dec2012 tmElements_t tm; @@ -305,17 +306,17 @@ tm.Day = 21; RTC.setAlarm(ALARM_1, makeTime(tm)); ``` -###enableAlarm(byte alarmNumber, byte alarmType) -#####Description +### enableAlarm(byte alarmNumber, byte alarmType) +##### Description Enable or disable the given alarm. -#####Syntax +##### Syntax `RTC.enableAlarm(alarmNumber, alarmType);` -#####Parameters +##### Parameters **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.) -#####Returns +##### Returns None. -#####Example +##### Example ```c++ //disable alarm-0 RTC.enableAlarm(ALARM_0, ALM_DISABLE); @@ -331,16 +332,16 @@ RTC.enableAlarm(ALARM_1, ALM_MATCH_MINUTES); RTC.enableAlarm(ALARM_1, ALM_MATCH_SECONDS); ``` -###alarm(byte alarmNumber) -#####Description +### alarm(byte alarmNumber) +##### Description 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. -#####Syntax +##### Syntax `RTC.alarm(byte alarmNumber);` -#####Parameters +##### Parameters **alarmNumber:** ALARM_0 or ALARM_1 *(byte)* -#####Returns +##### Returns True if the alarm was triggered, else false *(boolean)* -#####Example +##### Example ```c++ if ( RTC.alarm(ALARM_0) ) //alarm-0 has triggered @@ -348,54 +349,54 @@ else //alarm-0 has not triggered ``` -###alarmPolarity(boolean polarity) -#####Description +### alarmPolarity(boolean polarity) +##### Description Specifies 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. -#####Syntax +##### Syntax `RTC.alarmPolarity(boolean polarity);` -#####Parameters +##### Parameters **polarity:** HIGH or LOW *(boolean)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ RTC.alarmPolarity(HIGH); //drives MFP high when an alarm is triggered ``` -## Calibration, power failure, and other methods ## +## Calibration, power failure, and other methods -###calibWrite(int value) -#####Description +### calibWrite(int value) +##### Description 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. -#####Syntax +##### Syntax `RTC.calibWrite(int value);` -#####Parameters +##### Parameters **value:** The calibration value to set, between -127 and 127 *(int)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ 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. ``` -###calibRead(void) -#####Description +### calibRead(void) +##### Description Reads the RTC calibration register. -#####Syntax +##### Syntax `RTC.calibRead(void);` -#####Parameters +##### Parameters None. -#####Returns +##### Returns RTC calibration register value *(int)* -#####Example +##### Example ```c++ int value; value = RTC.calibRead(); ``` -###powerFail(time_t *powerDown, time_t *powerUp) -#####Description +### powerFail(time_t *powerDown, time_t *powerUp) +##### Description 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. @@ -403,14 +404,14 @@ Note that the power down and power up timestamp registers do not contain values 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. -#####Syntax +##### Syntax `RTC.powerFail(powerDown, powerUp);` -#####Parameters +##### Parameters **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. -#####Returns +##### Returns True if a power failure occurred, else false *(boolean)* -#####Example +##### Example ```c++ time_t powerDown, powerUp; //power outage timestamps if ( RTC.powerFail(&powerDown, &powerUp) ) { @@ -419,77 +420,77 @@ else //do something else ``` -###squareWave(byte freq) -#####Description +### squareWave(byte freq) +##### Description Enables or disables the square wave output on the multi-function pin (MFP). -#####Syntax +##### Syntax `RTC.squareWave(byte freq);` -#####Parameters +##### Parameters **freq:** One of the following: SQWAVE_1_HZ, SQWAVE_4096_HZ, SQWAVE_8192_HZ, SQWAVE_32768_HZ, SQWAVE_NONE *(byte)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ RTC.squareWave(SQWAVE_1_HZ); //output a 1Hz square wave on the MFP ``` -------------------------------------------------------------------------------- -###out(boolean level) -#####Description +### out(boolean level) +##### Description Sets 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. -#####Syntax +##### Syntax `RTC.out(boolean level);` -#####Parameters +##### Parameters **level**: HIGH or LOW *(boolean)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ RTC.out(LOW); //set the MFP to a low logic level ``` -------------------------------------------------------------------------------- -###idRead(byte *uniqueID) -#####Description +### idRead(byte *uniqueID) +##### Description Reads the 64-bit unique ID from the RTC. -#####Syntax +##### Syntax `RTC.idRead(byte *uniqueID);` -#####Parameters +##### Parameters **uniqueID:** An 8-byte array to receive the unique ID _(*byte)_ -#####Returns +##### Returns No function value returned. The RTC's ID is returned to the **uniqueID** array. -#####Example +##### Example ```c++ byte buf[8]; RTC.idRead(buf); ``` -------------------------------------------------------------------------------- -###vbaten(boolean enable) -#####Description +### vbaten(boolean enable) +##### Description 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. -#####Syntax +##### Syntax `RTC.vbaten(boolean enable);` -#####Parameters +##### Parameters **enable:** true or false *(boolean)* -#####Returns +##### Returns None. -#####Example +##### Example ```c++ RTC.vbaten(false); ``` -------------------------------------------------------------------------------- -###getEUI64(byte *uniqueID) -#####Description +### getEUI64(byte *uniqueID) +##### Description 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. -#####Syntax +##### Syntax `RTC.getEUI64(byte *uniqueID);` -#####Parameters +##### Parameters **uniqueID:** An 8-byte array to receive the EUI-64 unique ID _(*byte)_ -#####Returns +##### Returns No function value returned. The EUI-64 ID is returned to the **uniqueID** array. -#####Example +##### Example ```c++ byte buf[8]; RTC.getEUI64(buf); diff --git a/MCP79412RTC.cpp b/src/MCP79412RTC.cpp similarity index 100% rename from MCP79412RTC.cpp rename to src/MCP79412RTC.cpp diff --git a/MCP79412RTC.h b/src/MCP79412RTC.h similarity index 100% rename from MCP79412RTC.h rename to src/MCP79412RTC.h From 8bf0ca246adcbab91d44569c04337307784c2202 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 7 Apr 2018 17:04:23 -0400 Subject: [PATCH 04/22] Add library.properties file. --- README.md | 2 +- library.properties | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 library.properties diff --git a/README.md b/README.md index 7b7eeca..0f4091b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Arduino MCP79412 RTC Library v1.0 # +# Arduino MCP79412 RTC Library https://github.com/JChristensen/MCP79412RTC ReadMe file Jack Christensen diff --git a/library.properties b/library.properties new file mode 100644 index 0000000..85e438b --- /dev/null +++ b/library.properties @@ -0,0 +1,9 @@ +name=MCP79412RTC +version=1.0.1 +author=Jack Christensen +maintainer=Jack Christensen +sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. +paragraph=Requires the Arduino Time library, http://www.arduino.cc/playground/Code/Time +category=Timing +url=https://github.com/JChristensen/MCP79412RTC +architectures=avr From 9db9b68fe032af4dbc9559059895ab4690ddf57a Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 7 Apr 2018 17:31:01 -0400 Subject: [PATCH 05/22] Add GNU GPL 3.0 LICENSE.md file. Add CONTRIBUTING.md file. --- CONTRIBUTING.md | 18 ++ LICENSE.md | 686 +++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 693 insertions(+), 11 deletions(-) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c4cfc8c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# A GitHub Manifesto +### Notes on contributing to my repositories +Jack Christensen +Jan 2018 + +Surely Git and GitHub are wonderful tools. They make coding and collaboration so much easier. I'm equally impressed with the open source movement, and with the Arduino ecosystem in particular. + +I'm just one guy, mostly a hobbyist. Posting my projects to GitHub is my way of giving back a little to the community. It's very gratifying that some of my code has received a modicum of popularity. + +Like many things, this has been somewhat of a double-edged sword. Especially since I tend to be a pretty busy guy with many varied interests. + +First, I am always interested in bug reports. Please raise an issue in the appropriate repository and please please please include a good, concise description of the issue and a Short, Self Contained, Correct (Compilable), Example (see [sscce.org](http://www.sscce.org/)). I will need to be able to reproduce the issue, with minimal hardware, and without installing a dozen other libraries. I work exclusively with the AVR architecture so most times I will not be able to reproduce issues on other platforms. (There have been one or two occasions where relatively simple changes have been made to accommodate another platform; I am not necessarily averse to these.) + +Second, bug reports should always be for problems with *my* code. I will not use GitHub to help you with *your* code, even if you happen to be using one of my libraries. Please use the [Arduino forum](https://forum.arduino.cc/) or other such venue instead. + +Finally, pull requests can be problematic, especially if they represent enhancements rather than fixes. I seldom intend my code to be all things to all people. This is mostly a hobby activity and I have very limited bandwidth. Reviewing and managing PRs requires time that I do not often have. Sometimes a PR will take a library in a direction that I'm not interested in. Sometimes a PR will be counter to my original design intent. No doubt the author of a PR thinks that their new feature is the best thing since canned beer, but if I don't happen to share that opinion, then I'll decline it. OTOH, I am certainly capable of making stupid mistakes and missing absolutely fundamental things, and I do appreciate it when these are pointed out. + +All this to say, that if I do decline a request, please do not take it personally. Feel free to consider it my problem, not yours. At the end of the day, it's my code, and I reserve the right to decline issues or PRs for any reason, or for no reason at all. But here is the beauty of open source. You can always fork the repository and have your way with it. diff --git a/LICENSE.md b/LICENSE.md index 2b5eba5..2fb2e74 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,11 +1,675 @@ -# Arduino MCP79412 RTC Library v1.0 # -https://github.com/JChristensen/MCP79412RTC -LICENSE file -Jack Christensen Sep 2012 - -![CC BY-SA](http://mirrors.creativecommons.org/presskit/buttons/88x31/png/by-sa.png) -## CC BY-SA ## -Arduino MCP79412RTC Library by Jack Christensen is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to: -Creative Commons -444 Castro Street, Suite 900 -Mountain View, CA 94041 +### GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +### Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +### TERMS AND CONDITIONS + +#### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +#### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +#### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +#### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +#### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +#### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +#### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +#### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +#### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +#### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +#### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +#### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +#### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +#### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in +detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +#### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +#### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +#### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +### How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + 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 . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . From 0e92bdc4e6a978b7ce303fd58881e9b83e0db4b5 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 7 Apr 2018 17:40:26 -0400 Subject: [PATCH 06/22] Change to use TimeLib.h. Improved support for non-AVR architectures. Change license to GNU GPL 3.0. Move defines not needed in .h file to .cpp file. Update examples. Cosmetic and style changes. --- README.md | 52 +- .../PowerOutageLogger/PowerOutageLogger.ino | 196 +++++++ .../PowerOutageLogger/PowerOutageLogger.pde | 193 ------- examples/SetSerial/SetSerial.ino | 127 ++--- examples/TimeRTC/TimeRTC.ino | 50 ++ examples/TimeRTC/TimeRTC.pde | 48 -- examples/rtcSet1/rtcSet1.ino | 55 ++ examples/rtcSet1/rtcSet1.pde | 61 -- examples/rtcSet2/rtcSet2.ino | 52 ++ examples/rtcSet2/rtcSet2.pde | 59 -- examples/rtcSet3/rtcSet3.ino | 76 +++ examples/rtcSet3/rtcSet3.pde | 83 --- examples/rtcSetSerial/rtcSetSerial.ino | 112 ++++ examples/rtcSetSerial/rtcSetSerial.pde | 120 ---- .../tiny79412_KnockBang.ino | 71 ++- library.properties | 4 +- src/MCP79412RTC.cpp | 522 +++++++++--------- src/MCP79412RTC.h | 157 +++--- 18 files changed, 980 insertions(+), 1058 deletions(-) create mode 100644 examples/PowerOutageLogger/PowerOutageLogger.ino delete mode 100644 examples/PowerOutageLogger/PowerOutageLogger.pde create mode 100644 examples/TimeRTC/TimeRTC.ino delete mode 100644 examples/TimeRTC/TimeRTC.pde create mode 100644 examples/rtcSet1/rtcSet1.ino delete mode 100644 examples/rtcSet1/rtcSet1.pde create mode 100644 examples/rtcSet2/rtcSet2.ino delete mode 100644 examples/rtcSet2/rtcSet2.pde create mode 100644 examples/rtcSet3/rtcSet3.ino delete mode 100644 examples/rtcSet3/rtcSet3.pde create mode 100644 examples/rtcSetSerial/rtcSetSerial.ino delete mode 100644 examples/rtcSetSerial/rtcSetSerial.pde diff --git a/README.md b/README.md index 0f4091b..16bbcc5 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,24 @@ # Arduino MCP79412 RTC Library https://github.com/JChristensen/MCP79412RTC -ReadMe file +README file Jack Christensen -Sep-2012 - -![CC BY-SA](http://mirrors.creativecommons.org/presskit/buttons/80x15/png/by-sa.png) +Sep 2012 ## Introduction -**MCP79412RTC** is an Arduino library that supports the Microchip MCP7941x Real-Time Clock/Calendar chips. It is intended to be used with the [Arduino Time library] (http://www.arduino.cc/playground/Code/Time). +**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](https://github.com/PaulStoffregen/Time). -The **MCP79412RTC** library is a drop-in replacement for the **DS1307RTC** library by Michael Margolis that is supplied with the [Arduino Time library](http://www.arduino.cc/playground/Code/Time). To change from using a DS1307 RTC to an MCP7941x RTC, it is only necessary to use `#include ` instead of `#include `. +The **MCP79412RTC** library is a drop-in replacement for the (older) **DS1307RTC** library by Michael Margolis that is supplied with the [Arduino Time library](https://www.arduino.cc/playground/Code/Time) (but not for [PJRC's newer version of the DS1307RTC library](https://www.pjrc.com/teensy/td_libs_DS1307RTC.html)). To change from using a DS1307 RTC to an MCP7941x RTC, it is only necessary to use `#include ` instead of `#include `. -The **MCP79412RTC** library also implements methods to support the additional features of the MCP7941x RTC. +The **MCP79412RTC** library also implements functions to support the additional features of the MCP7941x RTC. **For more information on the MCP79412, see:** [My Blog Post](http://goo.gl/MkBnjR), summarizing the features and advantages of the MCP79412 [My Power Outage Logger Project](http://goo.gl/RfM5os), an Arduino-based project featuring the MCP79412 The [Microchip MCP79412 Product Page](http://goo.gl/SHfKe0) for specs, datasheet, etc. -MCP79411 and MCP79412 breakout boards are available at [my Tindie Store](http://goo.gl/UzAVcZ) - -## Installation -To use the **MCP79412RTC** library: -- Go to https://github.com/JChristensen/MCP79412RTC, click the **Download ZIP** button and save the ZIP file to a convenient location on your PC. -- Uncompress the downloaded file. This will result in a folder containing all the files for the library, that has a name that includes the branch name, usually **MCP79412RTC-master**. -- Rename the folder to just **MCP79412RTC**. -- Copy the renamed folder to the Arduino sketchbook\libraries folder. ## Examples 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. @@ -40,16 +31,9 @@ The following example sketches are included with the **MCP79412RTC** library: ## Usage notes Similar to the **DS1307RTC** library, the **MCP79412RTC** library instantiates an RTC object; the user does not need to do this. -To use the **MCP79412RTC** library, the Time and Wire libraries must also be included. For brevity, these includes are not repeated in the examples below: -```c++ -#include //http://github.com/JChristensen/MCP79412RTC -#include //http://www.arduino.cc/playground/Code/Time -#include //http://arduino.cc/en/Reference/Wire (included with Arduino IDE) -``` - -## Methods for setting and reading the time +## Functions for setting and reading the time -### get(void) +### get() ##### Description 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.). ##### Syntax @@ -84,7 +68,7 @@ RTC.set(now()); //set the RTC from the system time ### read(tmElements_t &tm) ##### Description -Reads 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](http://www.arduino.cc/playground/Code/Time) for details on the *tmElements_t* structure. +Reads 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](https://www.arduino.cc/playground/Code/Time) for details on the *tmElements_t* structure. ##### Syntax `RTC.read(tm);` ##### Parameters @@ -123,7 +107,7 @@ tm.Year = 2009 - 1970; //tmElements_t.Year is the offset from 1970 RTC.write(tm); //set the RTC from the tm structure ``` -### isRunning(void) +### isRunning() ##### Description Returns 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. ##### Syntax @@ -140,8 +124,8 @@ else //do something else ``` -## Methods for reading and writing static RAM (SRAM) -The MCP79412 RTC has 64 bytes of battery-backed SRAM that can be read and written with the following methods using addresses between 0 and 63. Addresses passed to these functions are constrained to the valid range by an AND function. +## Functions for reading and writing static RAM (SRAM) +The 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. ### sramWrite(byte addr, byte value) ##### Description @@ -209,8 +193,8 @@ byte buf[8]; RTC.sramRead(56, buf, 8); ``` -## Methods for Reading and writing EEPROM -The MCP79412 RTC has 128 bytes of non-volatile EEPROM that can be read and written with the following methods using addresses between 0 and 127. Addresses passed to these functions are constrained to the valid range by an AND function. +## Functions for Reading and writing EEPROM +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. @@ -280,7 +264,7 @@ byte buf[8]; RTC.eepromRead(120, buf, 8); ``` -## Alarm methods +## Alarm functions The 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. ### setAlarm(byte alarmNumber, time_t alarmTime) @@ -363,7 +347,7 @@ None. RTC.alarmPolarity(HIGH); //drives MFP high when an alarm is triggered ``` -## Calibration, power failure, and other methods +## Calibration, power failure, and other functions ### calibWrite(int value) ##### Description @@ -380,11 +364,11 @@ 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. ``` -### calibRead(void) +### calibRead() ##### Description Reads the RTC calibration register. ##### Syntax -`RTC.calibRead(void);` +`RTC.calibRead();` ##### Parameters None. ##### Returns diff --git a/examples/PowerOutageLogger/PowerOutageLogger.ino b/examples/PowerOutageLogger/PowerOutageLogger.ino new file mode 100644 index 0000000..a2e925d --- /dev/null +++ b/examples/PowerOutageLogger/PowerOutageLogger.ino @@ -0,0 +1,196 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch: Power Outage Logger using Microchip MCP79412 RTC. +// Assumes the RTC is running and set to UTC. +// A maximum of 7 outages (power down/up times) can be logged in the +// RTC's SRAM. +// +// Jack Christensen 23Aug2012 + +#include // https://github.com/JChristensen/MCP79412RTC +#include // http://arduiniana.org/libraries/streaming/ +#include // https://github.com/PaulStoffregen/Time +#include // https://github.com/JChristensen/Timezone + +#define FIRST_OUTAGE_ADDR 0x08 // address of first outage timestamps in RTC SRAM +#define OUTAGE_LENGTH 8 // 8 data bytes for each outage (start and end timestamps, both are time_t values) +#define MAX_OUTAGES 7 // maximum number of outage timestamp pairs that can be stored in SRAM +#define MAX_OUTAGE_ADDR FIRST_OUTAGE_ADDR + OUTAGE_LENGTH * (MAX_OUTAGES - 1) // last outage address +#define APP_ID 1 // APP_ID and 4 bytes of the RTC ID are stored in sram to provide + // a way to recognize that the logging data structure has been initialized +#define RTC_ID_LO 0x00 // lower 4 bytes of RTC unique ID are stored at sram addr 0x00 +#define APP_ID_ADDR 0x04 // address of appID (1) +#define NBR_OUTAGES_ADDR 0x05 // address containing number of outages currently stored in SRAM +#define NEXT_OUTAGE_ADDR 0x06 // address containing pointer to next outage +#define RFU_ADDR 0x07 // reserved for future use + +// US Eastern Time Zone (New York, Detroit) +TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; // Daylight time = UTC - 4 hours +TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; // Standard time = UTC - 5 hours +Timezone myTZ(myDST, mySTD); +TimeChangeRule *tcr; // pointer to the time change rule, used to get TZ abbrev +time_t utc, local, lastUTC; + +void setup() +{ + Serial.begin(115200); + + setSyncProvider(RTC.get); // the function to get the time from the RTC + Serial << "RTC SYNC"; + if (timeStatus()!= timeSet) Serial << " FAIL"; + Serial << endl; + + //logClear(); + logOutage(); +} + +void loop() +{ + // nothing here in loop() has anything to do with logging power outages, + // we just print the time every second so that something is happening. + utc = now(); + if (utc != lastUTC) + { + lastUTC = utc; + local = myTZ.toLocal(utc, &tcr); + Serial << endl; + printTime(utc, "UTC"); + printTime(local, tcr -> abbrev); + } +} + +// initialize the log data structure in the RTC SRAM if needed. +// log a new outage if one occurred. +// print out the outages logged. +void logOutage() +{ + union { + uint8_t b[8]; + struct { + uint32_t hi; + uint32_t lo; + }; + } uniqueID; // 8-byte RTC "unique ID" with access to upper and lower halves + + uint32_t loID; // lower half of the unique ID read from sram + uint8_t appID; // app ID read from sram + uint8_t nOutage; // number of outages stored in sram + uint8_t nextOutage; // address of next outage timestamps in sram + uint8_t outageAddr; // outage address in sram + time_t powerDown, powerUp; // power outage timestamps + + RTC.idRead(uniqueID.b); // get the RTC's ID + loID = read32(RTC_ID_LO); // if already initialized, the lower half of the ID is stored at SRAM addr 0x00, + appID = RTC.sramRead(APP_ID_ADDR); // and the app ID (1) is at addr 0x04. + Serial << "RTC ID"; + for (uint8_t i=0; i<8; i++) + { + Serial << (uniqueID.b[i] < 16 ? " 0" : " ") << _HEX(uniqueID.b[i]); + } + + if ( loID != uniqueID.lo || appID != 1 ) // logging initialized? + { + write32(RTC_ID_LO, uniqueID.lo); // least significant half of the RTC unique ID + RTC.sramWrite(APP_ID_ADDR, APP_ID); // app ID + RTC.sramWrite(NBR_OUTAGES_ADDR, 0); // number of outages + RTC.sramWrite(NEXT_OUTAGE_ADDR, FIRST_OUTAGE_ADDR); // next location for outage times + RTC.sramWrite(RFU_ADDR, 0); // reserved for future use + Serial << "Logging initialized" << endl; // no, do it now + } + + // if an outage has occurred, record it + if ( RTC.powerFail(&powerDown, &powerUp) ) + { + nOutage = RTC.sramRead(NBR_OUTAGES_ADDR); + nextOutage = RTC.sramRead(NEXT_OUTAGE_ADDR); + write32(nextOutage, powerDown); + write32(nextOutage + 4, powerUp); + nextOutage += OUTAGE_LENGTH; + if (nextOutage > MAX_OUTAGE_ADDR) nextOutage = FIRST_OUTAGE_ADDR; + RTC.sramWrite(NEXT_OUTAGE_ADDR, nextOutage); + if (nOutage < MAX_OUTAGES) RTC.sramWrite(NBR_OUTAGES_ADDR, ++nOutage); + } + + // print out all the outages logged + nOutage = RTC.sramRead(NBR_OUTAGES_ADDR); + nextOutage = RTC.sramRead(NEXT_OUTAGE_ADDR); + outageAddr = nextOutage - OUTAGE_LENGTH; + if (outageAddr < FIRST_OUTAGE_ADDR) outageAddr = MAX_OUTAGE_ADDR; + Serial << endl << endl << "Power outages logged: " << _DEC(nOutage) << endl; + for (uint8_t i=nOutage; i>0; i--) + { + powerDown = read32(outageAddr); + powerUp = read32(outageAddr + 4); + Serial << endl << _DEC(i) << ": Power down "; + printTime(myTZ.toLocal(powerDown, &tcr), tcr -> abbrev); + Serial << _DEC(i) << ": Power up "; + printTime(myTZ.toLocal(powerUp, &tcr), tcr -> abbrev); + outageAddr -= OUTAGE_LENGTH; + if (outageAddr < FIRST_OUTAGE_ADDR) outageAddr = MAX_OUTAGE_ADDR; + } +} + +// initialize the logging data structure and log data +void logClear() +{ + for (uint8_t i=0; i //http://github.com/JChristensen/MCP79412RTC -#include //http://arduiniana.org/libraries/streaming/ -#include //http://www.arduino.cc/playground/Code/Time -#include //http://github.com/JChristensen/Timezone -#include //http://arduino.cc/en/Reference/Wire (included with Arduino IDE) - -#define FIRST_OUTAGE_ADDR 0x08 //address of first outage timestamps in RTC SRAM -#define OUTAGE_LENGTH 8 //8 data bytes for each outage (start and end timestamps, both are time_t values) -#define MAX_OUTAGES 7 //maximum number of outage timestamp pairs that can be stored in SRAM -#define MAX_OUTAGE_ADDR FIRST_OUTAGE_ADDR + OUTAGE_LENGTH * (MAX_OUTAGES - 1) //last outage address -#define APP_ID 1 //APP_ID and 4 bytes of the RTC ID are stored in sram to provide - //a way to recognize that the logging data structure has been initialized -#define RTC_ID_LO 0x00 //lower 4 bytes of RTC unique ID are stored at sram addr 0x00 -#define APP_ID_ADDR 0x04 //address of appID (1) -#define NBR_OUTAGES_ADDR 0x05 //address containing number of outages currently stored in SRAM -#define NEXT_OUTAGE_ADDR 0x06 //address containing pointer to next outage -#define RFU_ADDR 0x07 //reserved for future use - -//US Eastern Time Zone (New York, Detroit) -TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; //Daylight time = UTC - 4 hours -TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; //Standard time = UTC - 5 hours -Timezone myTZ(myDST, mySTD); -TimeChangeRule *tcr; //pointer to the time change rule, used to get TZ abbrev -time_t utc, local, lastUTC; - -void setup() { - Serial.begin(115200); - - setSyncProvider(RTC.get); //the function to get the time from the RTC - Serial << "RTC SYNC"; - if (timeStatus()!= timeSet) Serial << " FAIL"; - Serial << endl; - - //logClear(); - logOutage(); -} - -void loop() -{ - //nothing here in loop() has anything to do with logging power outages, - //we just print the time every second so that something is happening. - utc = now(); - if (utc != lastUTC) { - lastUTC = utc; - local = myTZ.toLocal(utc, &tcr); - Serial << endl; - printTime(utc, "UTC"); - printTime(local, tcr -> abbrev); - } -} - -//initialize the log data structure in the RTC SRAM if needed. -//log a new outage if one occurred. -//print out the outages logged. -void logOutage(void) -{ - union { - uint8_t b[8]; - struct { - uint32_t hi; - uint32_t lo; - }; - } uniqueID; //8-byte RTC "unique ID" with access to upper and lower halves - - uint32_t loID; //lower half of the unique ID read from sram - uint8_t appID; //app ID read from sram - uint8_t nOutage; //number of outages stored in sram - uint8_t nextOutage; //address of next outage timestamps in sram - uint8_t outageAddr; //outage address in sram - time_t powerDown, powerUp; //power outage timestamps - - RTC.idRead(uniqueID.b); //get the RTC's ID - loID = read32(RTC_ID_LO); //if already initialized, the lower half of the ID is stored at SRAM addr 0x00, - appID = RTC.sramRead(APP_ID_ADDR); //and the app ID (1) is at addr 0x04. - Serial << "RTC ID"; - for (uint8_t i=0; i<8; i++) { - Serial << (uniqueID.b[i] < 16 ? " 0" : " ") << _HEX(uniqueID.b[i]); - } - - if ( loID != uniqueID.lo || appID != 1 ) { //logging initialized? - write32(RTC_ID_LO, uniqueID.lo); //least significant half of the RTC unique ID - RTC.sramWrite(APP_ID_ADDR, APP_ID); //app ID - RTC.sramWrite(NBR_OUTAGES_ADDR, 0); //number of outages - RTC.sramWrite(NEXT_OUTAGE_ADDR, FIRST_OUTAGE_ADDR); //next location for outage times - RTC.sramWrite(RFU_ADDR, 0); //reserved for future use - Serial << "Logging initialized" << endl; //no, do it now - } - - //if an outage has occurred, record it - if ( RTC.powerFail(&powerDown, &powerUp) ) { - nOutage = RTC.sramRead(NBR_OUTAGES_ADDR); - nextOutage = RTC.sramRead(NEXT_OUTAGE_ADDR); - write32(nextOutage, powerDown); - write32(nextOutage + 4, powerUp); - nextOutage += OUTAGE_LENGTH; - if (nextOutage > MAX_OUTAGE_ADDR) nextOutage = FIRST_OUTAGE_ADDR; - RTC.sramWrite(NEXT_OUTAGE_ADDR, nextOutage); - if (nOutage < MAX_OUTAGES) RTC.sramWrite(NBR_OUTAGES_ADDR, ++nOutage); - } - - //print out all the outages logged - nOutage = RTC.sramRead(NBR_OUTAGES_ADDR); - nextOutage = RTC.sramRead(NEXT_OUTAGE_ADDR); - outageAddr = nextOutage - OUTAGE_LENGTH; - if (outageAddr < FIRST_OUTAGE_ADDR) outageAddr = MAX_OUTAGE_ADDR; - Serial << endl << endl << "Power outages logged: " << _DEC(nOutage) << endl; - for (uint8_t i=nOutage; i>0; i--) { - powerDown = read32(outageAddr); - powerUp = read32(outageAddr + 4); - Serial << endl << _DEC(i) << ": Power down "; - printTime(myTZ.toLocal(powerDown, &tcr), tcr -> abbrev); - Serial << _DEC(i) << ": Power up "; - printTime(myTZ.toLocal(powerUp, &tcr), tcr -> abbrev); - outageAddr -= OUTAGE_LENGTH; - if (outageAddr < FIRST_OUTAGE_ADDR) outageAddr = MAX_OUTAGE_ADDR; - } -} - -//destroy the logging data structure and log data -void logClear(void) -{ - for (uint8_t i=0; i //http://github.com/JChristensen/MCP79412RTC -#include //http://arduiniana.org/libraries/streaming/ -#include //http://playground.arduino.cc/Code/Time -#include //http://arduino.cc/en/Reference/Wire - -void setup(void) +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch. Displays the date and time from an MCP79412 RTC +// every second. +// +// Set the date and time by entering the following on the Arduino +// serial monitor: +// Syear,month,day,hour,minute,second, +// +// Where +// year can be two or four digits, +// month is 1-12, +// day is 1-31, +// hour is 0-23, and +// minute and second are 0-59. +// +// Set the calibration register by entering the following: +// Cnnn, +// +// Where nnn can be a positive or negative value, e.g. "c4" or "c-42". +// +// Entering the final comma delimiter (after "second") will avoid a +// one-second timeout and will allow the RTC to be set more accurately. +// +// No validity checking is done, invalid values or incomplete syntax +// in the input will result in an incorrect RTC setting. +// +// Jack Christensen 28Aug2013 + +#include // https://github.com/JChristensen/MCP79412RTC +#include // http://arduiniana.org/libraries/streaming/ +#include // https://github.com/PaulStoffregen/Time + +void setup() { byte rtcID[8]; - + Serial.begin(115200); - - //setSyncProvider() causes the Time library to synchronize with the - //external RTC by calling RTC.get() every five minutes by default. + + // setSyncProvider() causes the Time library to synchronize with the + // external RTC by calling RTC.get() every five minutes by default. setSyncProvider(RTC.get); Serial << endl << F("RTC Sync"); if (timeStatus() != timeSet) Serial << F(" FAIL!"); Serial << endl; - + RTC.idRead(rtcID); Serial << F("RTC ID = "); for (int i=0; i<8; ++i) { @@ -67,27 +62,27 @@ void setup(void) Serial << _HEX(rtcID[i]); } Serial << endl; - + Serial << F("Calibration Register = ") << RTC.calibRead() << endl; } -void loop(void) +void loop() { static time_t tLast; time_t t; tmElements_t tm; int cmdChar, y, oldCal, newCal; - //check for input, first character is a command, "S" to set date/time, or "C" to set the calibration register + // check for input, first character is a command, "S" to set date/time, or "C" to set the calibration register if (Serial.available()) { cmdChar = Serial.read(); - + switch (cmdChar) { case 'S': case 's': - //note that the tmElements_t Year member is an offset from 1970, - //but the RTC wants the last two digits of the calendar year. - //use the convenience macros from Time.h to do the conversions. + // note that the tmElements_t Year member is an offset from 1970, + // but the RTC wants the last two digits of the calendar year. + // use the convenience macros from TimeLib.h to do the conversions. y = Serial.parseInt(); if (y >= 100 && y < 1000) Serial << F("Error: Year must be two digits or four digits!") << endl; @@ -102,8 +97,8 @@ void loop(void) tm.Minute = Serial.parseInt(); tm.Second = Serial.parseInt(); t = makeTime(tm); - RTC.set(t); //use the time_t value to ensure correct weekday is set - setTime(t); + RTC.set(t); // use the time_t value to ensure correct weekday is set + setTime(t); Serial << F("RTC set to: "); printDateTime(t); Serial << endl; @@ -117,16 +112,16 @@ void loop(void) RTC.calibWrite(newCal); Serial << F("Calibration changed from ") << oldCal << F(" to ") << RTC.calibRead() << endl; break; - + default: Serial << endl << F("Unrecognized command: ") << (char)cmdChar << endl; break; } - //dump any extraneous input + // dump any extraneous input while (Serial.available() > 0) Serial.read(); } - + t = now(); if (t != tLast) { tLast = t; @@ -135,7 +130,7 @@ void loop(void) } } -//print date and time to Serial +// print date and time to Serial void printDateTime(time_t t) { printDate(t); @@ -143,7 +138,7 @@ void printDateTime(time_t t) printTime(t); } -//print time to Serial +// print time to Serial void printTime(time_t t) { printI00(hour(t), ':'); @@ -151,20 +146,20 @@ void printTime(time_t t) printI00(second(t), ' '); } -//print date to Serial +// print date to Serial void printDate(time_t t) { printI00(day(t), 0); Serial << monthShortStr(month(t)) << _DEC(year(t)); } -//Print an integer in "00" format (with leading zero), -//followed by a delimiter character to Serial. -//Input value assumed to be between 0 and 99. +// Print an integer in "00" format (with leading zero), +// followed by a delimiter character to Serial. +// Input value assumed to be between 0 and 99. void printI00(int val, char delim) { if (val < 10) Serial << '0'; Serial << _DEC(val); if (delim > 0) Serial << delim; return; -} \ No newline at end of file +} diff --git a/examples/TimeRTC/TimeRTC.ino b/examples/TimeRTC/TimeRTC.ino new file mode 100644 index 0000000..3f730ae --- /dev/null +++ b/examples/TimeRTC/TimeRTC.ino @@ -0,0 +1,50 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// TimeRTC.ino +// Example code illustrating Time library with Real Time Clock. +// This example is identical to the example provided with the Time Library, +// only the #include statement has been changed to include the MCP79412RTC library. + +#include // http://github.com/JChristensen/MCP79412RTC +#include // https://www.pjrc.com/teensy/td_libs_DS1307RTC.html +#include // https://www.arduino.cc/en/Reference/Wire + +void setup() +{ + Serial.begin(9600); + setSyncProvider(RTC.get); // the function to get the time from the RTC + if(timeStatus()!= timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); +} + +void loop() +{ + digitalClockDisplay(); + delay(1000); +} + +void digitalClockDisplay() +{ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits) +{ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} diff --git a/examples/TimeRTC/TimeRTC.pde b/examples/TimeRTC/TimeRTC.pde deleted file mode 100644 index 0a44862..0000000 --- a/examples/TimeRTC/TimeRTC.pde +++ /dev/null @@ -1,48 +0,0 @@ -/* - * TimeRTC.pde - * Example code illustrating Time library with Real Time Clock. - * This example is identical to the example provided with the Time Library, - * only the #include statement has been changed to include the MCP79412RTC library. - */ - -#include -#include -#include //http://github.com/JChristensen/MCP79412RTC - -void setup() { - Serial.begin(9600); - setSyncProvider(RTC.get); // the function to get the time from the RTC - if(timeStatus()!= timeSet) - Serial.println("Unable to sync with the RTC"); - else - Serial.println("RTC has set the system time"); -} - -void loop() -{ - digitalClockDisplay(); - delay(1000); -} - -void digitalClockDisplay(){ - // digital clock display of the time - Serial.print(hour()); - printDigits(minute()); - printDigits(second()); - Serial.print(" "); - Serial.print(day()); - Serial.print(" "); - Serial.print(month()); - Serial.print(" "); - Serial.print(year()); - Serial.println(); -} - -void printDigits(int digits){ - // utility function for digital clock display: prints preceding colon and leading 0 - Serial.print(":"); - if(digits < 10) - Serial.print('0'); - Serial.print(digits); -} - diff --git a/examples/rtcSet1/rtcSet1.ino b/examples/rtcSet1/rtcSet1.ino new file mode 100644 index 0000000..8fe845d --- /dev/null +++ b/examples/rtcSet1/rtcSet1.ino @@ -0,0 +1,55 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch to set the RTC date and time to a hard-coded value. +// This is just a simple demonstration of setting the RTC time. +// Note that each time the sketch is run (or the microcontroller is +// reset), the RTC will be set to the same hard-coded time, so this +// example may be of limited usefulness as an actual clock. + +#include // https://github.com/JChristensen/MCP79412RTC +#include // https://github.com/PaulStoffregen/Time + +void setup() +{ + delay(2000); + Serial.begin(9600); + + setTime(23, 31, 30, 13, 2, 2009); // set the system time to 23h31m30s on 13Feb2009 + // the setTime() function is from the Time.h library. + // setTime(hour, minute, second, day, month, year); + RTC.set(now()); // set the RTC from the system time +} + +void loop() +{ + printTime(now()); + delay(1000); +} + +// Print time (and date) given a time_t value +void printTime(time_t t) +{ + printI00(hour(t), ':'); + printI00(minute(t), ':'); + printI00(second(t), ' '); + Serial.print(dayShortStr(weekday(t))); + Serial.print(' '); + printI00(day(t), ' '); + Serial.print(monthShortStr(month(t))); + Serial.print(' '); + Serial.println(year(t)); +} + +// Print an integer in "00" format (with leading zero), +// followed by a delimiter. +// Input value assumed to be between 0 and 99. +void printI00(int val, char delim) +{ + if (val < 10) Serial.print('0'); + Serial.print(val); + Serial.print(delim); + return; +} diff --git a/examples/rtcSet1/rtcSet1.pde b/examples/rtcSet1/rtcSet1.pde deleted file mode 100644 index 3c24d37..0000000 --- a/examples/rtcSet1/rtcSet1.pde +++ /dev/null @@ -1,61 +0,0 @@ -/*----------------------------------------------------------------------* - * Example sketch for Arduino MCP79412 Library by Jack Christensen * - * * - * Sets the RTC date and time to a hard-coded value. * - * This is just a simple demonstration of setting the RTC time. * - * Note that each time the sketch is run (or the microcontroller is * - * reset), the RTC will be set to the same hard-coded time, so this * - * example may be of limited usefulness as an actual clock. * - * * - * This work is licensed under the Creative Commons Attribution- * - * ShareAlike 3.0 Unported License. To view a copy of this license, * - * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * - * letter to Creative Commons, 171 Second Street, Suite 300, * - * San Francisco, California, 94105, USA. * - *----------------------------------------------------------------------*/ - -#include //http://github.com/JChristensen/MCP79412RTC -#include //http://www.arduino.cc/playground/Code/Time -#include //http://arduino.cc/en/Reference/Wire (included with Arduino IDE) - -void setup(void) -{ - delay(2000); - Serial.begin(9600); - - setTime(23, 31, 30, 13, 2, 2009); //set the system time to 23h31m30s on 13Feb2009 - //the setTime() function is from the Time.h library. - //setTime(hour, minute, second, day, month, year); - RTC.set(now()); //set the RTC from the system time -} - -void loop(void) -{ - printTime(now()); - delay(1000); -} - -//Print time (and date) given a time_t value -void printTime(time_t t) -{ - printI00(hour(t), ':'); - printI00(minute(t), ':'); - printI00(second(t), ' '); - Serial.print(dayShortStr(weekday(t))); - Serial.print(' '); - printI00(day(t), ' '); - Serial.print(monthShortStr(month(t))); - Serial.print(' '); - Serial.println(year(t)); -} - -//Print an integer in "00" format (with leading zero), -//followed by a delimiter. -//Input value assumed to be between 0 and 99. -void printI00(int val, char delim) -{ - if (val < 10) Serial.print('0'); - Serial.print(val); - Serial.print(delim); - return; -} diff --git a/examples/rtcSet2/rtcSet2.ino b/examples/rtcSet2/rtcSet2.ino new file mode 100644 index 0000000..d5a4d40 --- /dev/null +++ b/examples/rtcSet2/rtcSet2.ino @@ -0,0 +1,52 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch to set the RTC date and time to a hard-coded value, +// using a tmElements_t structure. The same structure is then used to +// read the RTC once per second. This sketch only uses the Time +// library for the tmElements_t definition. +// +// This is just a simple demonstration of setting the RTC time. +// Note that each time the sketch is run (or the microcontroller is +// reset), the RTC will be set to the same hard-coded time, so this +// example may be of limited usefulness as an actual clock. + +#include // https://github.com/JChristensen/MCP79412RTC +#include // https://github.com/PaulStoffregen/Time + +tmElements_t tm; + +void setup() +{ + delay(2000); + Serial.begin(9600); + + tm.Hour = 23; // set the tm structure to 23h31m30s on Fri 13Feb2009 + tm.Minute = 31; + tm.Second = 30; + tm.Year = 2009 - 1970; // tmElements_t.Year is the offset from 1970. + tm.Month = 2; + tm.Day = 13; + tm.Wday = dowFriday; // See enum in Time.h: Sun=1, Mon=2, ... Sat=7 + RTC.write(tm); // set the RTC from the tm structure +} + +void loop() +{ + RTC.read(tm); + Serial.print(tm.Hour, DEC); + Serial.print(':'); + Serial.print(tm.Minute,DEC); + Serial.print(':'); + Serial.print(tm.Second,DEC); + Serial.print(' '); + Serial.print(tm.Year + 1970, DEC); + Serial.print('-'); + Serial.print(tm.Month, DEC); + Serial.print('-'); + Serial.print(tm.Day, DEC); + Serial.println(); + delay(1000); +} diff --git a/examples/rtcSet2/rtcSet2.pde b/examples/rtcSet2/rtcSet2.pde deleted file mode 100644 index 9c33f65..0000000 --- a/examples/rtcSet2/rtcSet2.pde +++ /dev/null @@ -1,59 +0,0 @@ -/*----------------------------------------------------------------------* - * Example sketch for Arduino MCP79412 Library by Jack Christensen * - * * - * Sets the RTC date and time to a hard-coded value, using a * - * tmElements_t structure. The same structure is then used to * - * read the RTC once per second. This sketch only uses the Time * - * library for the tmElements_t definition. * - * * - * This is just a simple demonstration of setting the RTC time. * - * Note that each time the sketch is run (or the microcontroller is * - * reset), the RTC will be set to the same hard-coded time, so this * - * example may be of limited usefulness as an actual clock. * - * * - * This work is licensed under the Creative Commons Attribution- * - * ShareAlike 3.0 Unported License. To view a copy of this license, * - * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * - * letter to Creative Commons, 171 Second Street, Suite 300, * - * San Francisco, California, 94105, USA. * - *----------------------------------------------------------------------*/ - -#include //http://github.com/JChristensen/MCP79412RTC -#include //http://www.arduino.cc/playground/Code/Time -#include //http://arduino.cc/en/Reference/Wire (included with Arduino IDE) - -tmElements_t tm; - -void setup(void) -{ - delay(2000); - Serial.begin(9600); - - tm.Hour = 23; //set the tm structure to 23h31m30s on Fri 13Feb2009 - tm.Minute = 31; - tm.Second = 30; - tm.Year = 2009 - 1970; //tmElements_t.Year is the offset from 1970. - tm.Month = 2; - tm.Day = 13; - tm.Wday = dowFriday; //See enum in Time.h: Sun=1, Mon=2, ... Sat=7 - RTC.write(tm); //set the RTC from the tm structure -} - -void loop(void) -{ - RTC.read(tm); - Serial.print(tm.Hour, DEC); - Serial.print(':'); - Serial.print(tm.Minute,DEC); - Serial.print(':'); - Serial.print(tm.Second,DEC); - Serial.print(' '); - Serial.print(tm.Year + 1970, DEC); - Serial.print('-'); - Serial.print(tm.Month, DEC); - Serial.print('-'); - Serial.print(tm.Day, DEC); - Serial.println(); - delay(1000); -} - diff --git a/examples/rtcSet3/rtcSet3.ino b/examples/rtcSet3/rtcSet3.ino new file mode 100644 index 0000000..d9f6446 --- /dev/null +++ b/examples/rtcSet3/rtcSet3.ino @@ -0,0 +1,76 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch to set the RTC date and time to the sketch compile +// time. Re-running this sketch by pressing the reset button, etc., +// will cause the RTC time to be reset to the *same* compile time. +// Upload the sketch again to recompile it with the current time. + +#include // https://github.com/JChristensen/MCP79412RTC +#include // https://github.com/PaulStoffregen/Time + +void setup() +{ + delay(2000); + Serial.begin(9600); + + setTime(compileTime()); // set the system time to the sketch compile time + RTC.set(now()); // set the RTC from the system time +} + +void loop() +{ + printTime(now()); + delay(1000); +} + +// Function to return the compile date and time as a time_t value +time_t compileTime() +{ + const uint32_t FUDGE(15); // fudge factor to allow for compile time (seconds, YMMV) + char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec"; + char chMon[3], *m; + int d, y; + tmElements_t tm; + time_t t; + + strncpy(chMon, compDate, 3); + chMon[3] = '\0'; + m = strstr(months, chMon); + tm.Month = ((m - months) / 3 + 1); + + tm.Day = atoi(compDate + 4); + tm.Year = atoi(compDate + 7) - 1970; + tm.Hour = atoi(compTime); + tm.Minute = atoi(compTime + 3); + tm.Second = atoi(compTime + 6); + t = makeTime(tm); + return t + FUDGE; // add fudge factor to allow for compile time +} + +// Print time (and date) given a time_t value +void printTime(time_t t) +{ + printI00(hour(t), ':'); + printI00(minute(t), ':'); + printI00(second(t), ' '); + Serial.print(dayShortStr(weekday(t))); + Serial.print(' '); + printI00(day(t), ' '); + Serial.print(monthShortStr(month(t))); + Serial.print(' '); + Serial.println(year(t)); +} + +// Print an integer in "00" format (with leading zero), +// followed by a delimiter. +// Input value assumed to be between 0 and 99. +void printI00(int val, char delim) +{ + if (val < 10) Serial.print('0'); + Serial.print(val); + Serial.print(delim); + return; +} diff --git a/examples/rtcSet3/rtcSet3.pde b/examples/rtcSet3/rtcSet3.pde deleted file mode 100644 index 738240a..0000000 --- a/examples/rtcSet3/rtcSet3.pde +++ /dev/null @@ -1,83 +0,0 @@ -/*----------------------------------------------------------------------* - * Example sketch for Arduino MCP79412 Library by Jack Christensen * - * * - * Sets the RTC date and time to the sketch compile time. * - * Re-running this sketch by pressing the reset button, etc., will * - * cause the RTC time to be reset to the *same* compile time. * - * Upload the sketch again to recompile it with the current time. * - * * - * This work is licensed under the Creative Commons Attribution- * - * ShareAlike 3.0 Unported License. To view a copy of this license, * - * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * - * letter to Creative Commons, 171 Second Street, Suite 300, * - * San Francisco, California, 94105, USA. * - *----------------------------------------------------------------------*/ - -#include //http://github.com/JChristensen/MCP79412RTC -#include //http://www.arduino.cc/playground/Code/Time -#include //http://arduino.cc/en/Reference/Wire (included with Arduino IDE) - -void setup(void) -{ - delay(2000); - Serial.begin(9600); - - setTime(compileTime()); //set the system time to the sketch compile time - RTC.set(now()); //set the RTC from the system time -} - -void loop(void) -{ - printTime(now()); - delay(1000); -} - -//Function to return the compile date and time as a time_t value -time_t compileTime(void) -{ -#define FUDGE 15 //fudge factor to allow for compile time (seconds, YMMV) - - char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec"; - char chMon[3], *m; - int d, y; - tmElements_t tm; - time_t t; - - strncpy(chMon, compDate, 3); - chMon[3] = '\0'; - m = strstr(months, chMon); - tm.Month = ((m - months) / 3 + 1); - - tm.Day = atoi(compDate + 4); - tm.Year = atoi(compDate + 7) - 1970; - tm.Hour = atoi(compTime); - tm.Minute = atoi(compTime + 3); - tm.Second = atoi(compTime + 6); - t = makeTime(tm); - return t + FUDGE; //add fudge factor to allow for compile time -} - -//Print time (and date) given a time_t value -void printTime(time_t t) -{ - printI00(hour(t), ':'); - printI00(minute(t), ':'); - printI00(second(t), ' '); - Serial.print(dayShortStr(weekday(t))); - Serial.print(' '); - printI00(day(t), ' '); - Serial.print(monthShortStr(month(t))); - Serial.print(' '); - Serial.println(year(t)); -} - -//Print an integer in "00" format (with leading zero), -//followed by a delimiter. -//Input value assumed to be between 0 and 99. -void printI00(int val, char delim) -{ - if (val < 10) Serial.print('0'); - Serial.print(val); - Serial.print(delim); - return; -} diff --git a/examples/rtcSetSerial/rtcSetSerial.ino b/examples/rtcSetSerial/rtcSetSerial.ino new file mode 100644 index 0000000..e5ca204 --- /dev/null +++ b/examples/rtcSetSerial/rtcSetSerial.ino @@ -0,0 +1,112 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch to set the RTC by entering a "Set" command on the +// serial monitor. Use a 24-hour clock and enter the command +// (case sensitive) exactly as follows: Set yyyy-mm-dd hh:mm:ss + +#include // https://github.com/JChristensen/MCP79412RTC +#include // https://github.com/PaulStoffregen/Time + +const uint32_t PRINT_INTERVAL(1000); // ms between printing the time +uint32_t ms, msLast; + +void setup() +{ + delay(2000); + Serial.begin(9600); + + setSyncProvider(RTC.get); // the function to get the time from the RTC + Serial.print("RTC SYNC"); + if (timeStatus() != timeSet) Serial.print(" FAIL"); + Serial.println(); +} + +void loop() +{ + ms = millis(); + readCommand(); + if (ms - msLast >= PRINT_INTERVAL) { + msLast = ms; + printTime(now()); + } +} + +// Read command from the Arduino serial monitor to set the RTC. +// Case-sensitive and must be entered exactly as (24-hour clock): +// Set yyyy-mm-dd hh:mm:ss +void readCommand() +{ + char cmd[24] = "Set yyyy-mm-dd hh:mm:ss"; + static int i; + tmElements_t tmSet; + time_t tSet; + + if (Serial.available() >= 23) { // enough characters for the whole command? + i = 0; // yes, read the available characters + while (Serial.available() > 0) { + if (i >= sizeof(cmd) - 1) { // more than we can enjoy + flushInput(); // clear out the input buffer + Serial.print("Too long: "); + Serial.println(cmd); + return; + } + delay(2); //let the next character trickle in + cmd[i++] = char(Serial.read()); + } + cmd[i] = 0; //put in string terminator + + if (strncmp(cmd, "Set ", 4) == 0) { + tmSet.Year = 1000 * (cmd[4] - '0') + 100 * (cmd[5] - '0') + 10 * (cmd[6] - '0') + cmd[7] - '0' - 1970; + tmSet.Month = 10 * (cmd[9] - '0') + cmd[10] - '0'; + tmSet.Day = 10 * (cmd[12] - '0') + cmd[13] - '0'; + tmSet.Hour = 10 * (cmd[15] - '0') + cmd[16] - '0'; + tmSet.Minute = 10 * (cmd[18] - '0') + cmd[19] - '0'; + tmSet.Second = 10 * (cmd[21] - '0') + cmd[22] - '0'; + tSet = makeTime(tmSet); // convert to time_t + setTime(tSet); // set the system time + RTC.set(now()); // set the rtc + Serial.println("RTC set!"); + flushInput(); // discard any extraneous trailing characters + } + else { + Serial.print("Unknown: "); + Serial.println(cmd); + } + } +} + +void flushInput() +{ + do { + delay(2); + Serial.read(); + } while (Serial.available() > 0); +} + +// Print time (and date) given a time_t value +void printTime(time_t t) +{ + printI00(hour(t), ':'); + printI00(minute(t), ':'); + printI00(second(t), ' '); + Serial.print(dayShortStr(weekday(t))); + Serial.print(' '); + printI00(day(t), ' '); + Serial.print(monthShortStr(month(t))); + Serial.print(' '); + Serial.println(year(t)); +} + +// Print an integer in "00" format (with leading zero), +// followed by a delimiter. +// Input value assumed to be between 0 and 99. +void printI00(int val, char delim) +{ + if (val < 10) Serial.print('0'); + Serial.print(val); + Serial.print(delim); + return; +} diff --git a/examples/rtcSetSerial/rtcSetSerial.pde b/examples/rtcSetSerial/rtcSetSerial.pde deleted file mode 100644 index ec520ab..0000000 --- a/examples/rtcSetSerial/rtcSetSerial.pde +++ /dev/null @@ -1,120 +0,0 @@ -/*----------------------------------------------------------------------* - * Example sketch for Arduino MCP79412 Library by Jack Christensen * - * * - * Set the RTC by entering a "Set" command on the serial monitor. * - * Use a 24-hour clock and enter the command (case sensitive) exactly * - * as follows: Set yyyy-mm-dd hh:mm:ss * - * * - * This work is licensed under the Creative Commons Attribution- * - * ShareAlike 3.0 Unported License. To view a copy of this license, * - * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * - * letter to Creative Commons, 171 Second Street, Suite 300, * - * San Francisco, California, 94105, USA. * - *----------------------------------------------------------------------*/ - -#include //http://github.com/JChristensen/MCP79412RTC -#include //http://www.arduino.cc/playground/Code/Time -#include //http://arduino.cc/en/Reference/Wire (included with Arduino IDE) - -#define PRINT_INTERVAL 1000 //ms between printing the time - -unsigned long ms, msLast; - -void setup() -{ - delay(2000); - Serial.begin(9600); - - setSyncProvider(RTC.get); //the function to get the time from the RTC - Serial.print("RTC SYNC"); - if (timeStatus() != timeSet) Serial.print(" FAIL"); - Serial.println(); -} - -void loop(void) -{ - ms = millis(); - readCommand(); - if (ms - msLast >= PRINT_INTERVAL) { - msLast = ms; - printTime(now()); - } -} - -//Read command from the Arduino serial monitor to set the RTC. -//Case-sensitive and must be entered exactly as (24-hour clock): -// Set yyyy-mm-dd hh:mm:ss -void readCommand() -{ - char cmd[24] = "Set yyyy-mm-dd hh:mm:ss"; - static int i; - tmElements_t tmSet; - time_t tSet; - - if (Serial.available() >= 23) { //enough characters for the whole command? - i = 0; //yes, read the available characters - while (Serial.available() > 0) { - if (i >= sizeof(cmd) - 1) { //more than we can enjoy - flushInput(); //clear out the input buffer - Serial.print("Too long: "); - Serial.println(cmd); - return; - } - delay(2); //let the next character trickle in - cmd[i++] = char(Serial.read()); - } - cmd[i] = 0; //put in string terminator - - if (strncmp(cmd, "Set ", 4) == 0) { - tmSet.Year = 1000 * (cmd[4] - '0') + 100 * (cmd[5] - '0') + 10 * (cmd[6] - '0') + cmd[7] - '0' - 1970; - tmSet.Month = 10 * (cmd[9] - '0') + cmd[10] - '0'; - tmSet.Day = 10 * (cmd[12] - '0') + cmd[13] - '0'; - tmSet.Hour = 10 * (cmd[15] - '0') + cmd[16] - '0'; - tmSet.Minute = 10 * (cmd[18] - '0') + cmd[19] - '0'; - tmSet.Second = 10 * (cmd[21] - '0') + cmd[22] - '0'; - tSet = makeTime(tmSet); //convert to time_t - setTime(tSet); //set the system time - RTC.set(now()); //set the rtc - Serial.println("RTC set!"); - flushInput(); //discard any extraneous trailing characters - } - else { - Serial.print("Unknown: "); - Serial.println(cmd); - } - } -} - -void flushInput(void) -{ - do { - delay(2); - Serial.read(); - } while (Serial.available() > 0); -} - -//Print time (and date) given a time_t value -void printTime(time_t t) -{ - printI00(hour(t), ':'); - printI00(minute(t), ':'); - printI00(second(t), ' '); - Serial.print(dayShortStr(weekday(t))); - Serial.print(' '); - printI00(day(t), ' '); - Serial.print(monthShortStr(month(t))); - Serial.print(' '); - Serial.println(year(t)); -} - -//Print an integer in "00" format (with leading zero), -//followed by a delimiter. -//Input value assumed to be between 0 and 99. -void printI00(int val, char delim) -{ - if (val < 10) Serial.print('0'); - Serial.print(val); - Serial.print(delim); - return; -} - diff --git a/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino b/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino index 2d9a19f..9317cc7 100644 --- a/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino +++ b/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino @@ -1,44 +1,41 @@ -/*----------------------------------------------------------------------* - * Digital clock display using an MCP79412 Real-Time Clock/Calendar * - * and an ATtiny45/85 with a 1MHz system clock. * - * * - * Tested with Arduino 1.0.5. Also Arduino-Tiny Core, TinyISP, and * - * TinyDebugKnockBang from http://code.google.com/p/arduino-tiny/ * - * * - * Run TinyISP on an ATmega microcontroller that does not have an LED * - * connected to pin 13 (SCK). The LED causes problems because the SPI * - * pins are also the I2C pins on the ATtiny. Connect MISO, MOSI, SCK * - * on the ATmega to the corresponding pins on the ATtiny through 220Ω * - * resistors for safety. Use 4.7K pullup resistors on the ATtiny * - * I2C bus. * - * * - * Jack Christensen 21Aug2013 * - * * - * This work is licensed under the Creative Commons Attribution- * - * ShareAlike 3.0 Unported License. To view a copy of this license, * - * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * - * letter to Creative Commons, 171 Second Street, Suite 300, * - * San Francisco, California, 94105, USA. * - *----------------------------------------------------------------------*/ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch. Digital clock display using an MCP79412 Real-Time +// Clock/Calendar and an ATtiny45/85 with a 1MHz system clock. +// +// Tested with Arduino 1.8.5, and: +// ATTinyCore, https://github.com/SpenceKonde/ATTinyCore +// TinyISP, https://github.com/Coding-Badly/TinyISP +// +// Run TinyISP on an ATmega microcontroller that does not have an LED +// connected to pin 13 (SCK). The LED causes problems because the SPI +// pins are also the I2C pins on the ATtiny. Connect MISO, MOSI, SCK +// on the ATmega to the corresponding pins on the ATtiny through 220Ω +// resistors for safety. Use 4.7K pullup resistors on the ATtiny +// I2C bus. +// +// Jack Christensen 21Aug2013 -#include //http://github.com/JChristensen/MCP79412RTC -#include //http://playground.arduino.cc/Code/Time -#include //http://code.google.com/p/arduino-tiny/ -#include //http://playground.arduino.cc/Code/USIi2c +#include // https://github.com/JChristensen/MCP79412RTC +#include // https://github.com/PaulStoffregen/Time +#include // https://github.com/Coding-Badly/TinyDebugKnockBang -void setup(void) +void setup() { Debug.begin(250000); - - //setSyncProvider() causes the Time library to synchronize with the - //external RTC by calling RTC.get() every five minutes by default. + + // setSyncProvider() causes the Time library to synchronize with the + // external RTC by calling RTC.get() every five minutes by default. setSyncProvider(RTC.get); Debug.print(F("RTC Sync")); if (timeStatus() != timeSet) Debug.print(F(" FAIL!")); Debug.println(); } -void loop(void) +void loop() { static time_t tLast; @@ -50,7 +47,7 @@ void loop(void) } } -//print date and time to Serial +// print date and time to Serial void printDateTime(time_t t) { printDate(t); @@ -58,7 +55,7 @@ void printDateTime(time_t t) printTime(t); } -//print time to Serial +// print time to Serial void printTime(time_t t) { printI00(hour(t), ':'); @@ -66,7 +63,7 @@ void printTime(time_t t) printI00(second(t), ' '); } -//print date to Serial +// print date to Serial void printDate(time_t t) { printI00(day(t), 0); @@ -74,9 +71,9 @@ void printDate(time_t t) Debug.print(year(t), DEC); } -//Print an integer in "00" format (with leading zero), -//followed by a delimiter character to Serial. -//Input value assumed to be between 0 and 99. +// Print an integer in "00" format (with leading zero), +// followed by a delimiter character to Serial. +// Input value assumed to be between 0 and 99. void printI00(int val, char delim) { if (val < 10) Debug.print('0'); diff --git a/library.properties b/library.properties index 85e438b..10a07c1 100644 --- a/library.properties +++ b/library.properties @@ -1,9 +1,9 @@ name=MCP79412RTC -version=1.0.1 +version=1.1.0 author=Jack Christensen maintainer=Jack Christensen sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. -paragraph=Requires the Arduino Time library, http://www.arduino.cc/playground/Code/Time +paragraph=Requires PJRC's improved Arduino Time Library, https://github.com/PaulStoffregen/Time category=Timing url=https://github.com/JChristensen/MCP79412RTC architectures=avr diff --git a/src/MCP79412RTC.cpp b/src/MCP79412RTC.cpp index f29d3b4..9a72b11 100644 --- a/src/MCP79412RTC.cpp +++ b/src/MCP79412RTC.cpp @@ -1,29 +1,29 @@ -/*----------------------------------------------------------------------* - * MCP79412RTC.cpp - Arduino library for the Microchip MCP7941x * - * Real-Time Clocks. This library is intended for use with the Arduino * - * Time.h library, http://www.arduino.cc/playground/Code/Time * - * * - * This library is a drop-in replacement for the DS1307RTC.h library * - * by Michael Margolis that is supplied with the Arduino Time library * - * above. To change from using a DS1307 RTC to an MCP7941x RTC, it is * - * only necessary to change the #include statement to include this * - * library instead of DS1307RTC.h. * - * * - * In addition, this library implements functions to support the * - * additional features of the MCP7941x. * - * * - * Jack Christensen 29Jul2012 * - * * - * This work is licensed under the Creative Commons Attribution- * - * ShareAlike 3.0 Unported License. To view a copy of this license, * - * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * - * letter to Creative Commons, 171 Second Street, Suite 300, * - * San Francisco, California, 94105, USA. * - *----------------------------------------------------------------------*/ - -#include "MCP79412RTC.h" - -//define release-independent I2C functions +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Arduino library for the Microchip MCP7941x Real-Time Clocks. +// Requires PJRC's improved version of the Arduino Time Library, +// https://playground.arduino.cc/Code/Time +// https://github.com/PaulStoffregen/Time +// +// For AVR architecture, an MCP79412RTC object named RTC is instantiated +// by the library and I2C initialization occurs in the constructor; +// this is for backwards compatibility. +// For other architectures, the user needs to instantiate a MCP79412RTC +// object and optionally initialize the I2C bus by calling +// MCP79412RTC::begin(). The constructor has an optional bool parameter +// to indicate whether I2C initialization should occur in the +// constructor; this parameter defaults to true if not given. + +#if defined(ARDUINO) && ARDUINO >= 100 +#include +#else +#include +#endif + +// release-independent I2C functions #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) #include #define i2cBegin TinyWireM.begin @@ -50,19 +50,78 @@ #define i2cWrite Wire.send #endif -/*----------------------------------------------------------------------* - * Constructor. * - *----------------------------------------------------------------------*/ -MCP79412RTC::MCP79412RTC() +#include +#include // https://github.com/PaulStoffregen/Time + + +// MCP7941x I2C Addresses +#define RTC_ADDR 0x6F +#define EEPROM_ADDR 0x57 + +// MCP7941x Register Addresses +#define TIME_REG 0x00 // 7 registers, Seconds, Minutes, Hours, DOW, Date, Month, Year +#define DAY_REG 0x03 // the RTC Day register contains the OSCON, VBAT, and VBATEN bits +#define YEAR_REG 0x06 // RTC year register +#define CTRL_REG 0x07 // control register +#define CALIB_REG 0x08 // calibration register +#define UNLOCK_ID_REG 0x09 // unlock ID register +#define ALM0_REG 0x0A // alarm 0, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month +#define ALM1_REG 0x11 // alarm 1, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month +#define ALM0_DAY 0x0D // DOW register has alarm config/flag bits +#define PWRDWN_TS_REG 0x18 // power-down timestamp, 4 registers, Minutes, Hours, Date, Month +#define PWRUP_TS_REG 0x1C // power-up timestamp, 4 registers, Minutes, Hours, Date, Month +#define TIMESTAMP_SIZE 8 // number of bytes in the two timestamp registers +#define SRAM_START_ADDR 0x20 // first SRAM address +#define SRAM_SIZE 64 // number of bytes of SRAM +#define EEPROM_SIZE 128 // number of bytes of EEPROM +#define EEPROM_PAGE_SIZE 8 // number of bytes on an EEPROM page +#define UNIQUE_ID_ADDR 0xF0 // starting address for unique ID +#define UNIQUE_ID_SIZE 8 // number of bytes in unique ID + +// Control Register bits +#define OUT 7 // sets logic level on MFP when not used as square wave output +#define SQWE 6 // set to enable square wave output +#define ALM1 5 // alarm 1 is active +#define ALM0 4 // alarm 0 is active +#define EXTOSC 3 // set to drive the RTC registers from an external oscillator instead of a crystal +#define RS2 2 // RS2:0 set square wave output frequency: 0==1Hz, 1==4096Hz, 2==8192Hz, 3=32768Hz +#define RS1 1 +#define RS0 0 + +// Other Control Bits +#define ST 7 // Seconds register (TIME_REG) oscillator start/stop bit, 1==Start, 0==Stop +#define HR1224 6 // Hours register (TIME_REG+2) 12 or 24 hour mode (24 hour mode==0) +#define AMPM 5 // Hours register (TIME_REG+2) AM/PM bit for 12 hour mode +#define OSCON 5 // Day register (TIME_REG+3) oscillator running (set and cleared by hardware) +#define VBAT 4 // Day register (TIME_REG+3) set by hardware when Vcc fails and RTC runs on battery. + // VBAT is cleared by software, clearing VBAT also clears the timestamp registers +#define VBATEN 3 // Day register (TIME_REG+3) VBATEN==1 enables backup battery, VBATEN==0 disconnects the VBAT pin (e.g. to save battery) +#define LP 5 // Month register (TIME_REG+5) leap year bit + +// Alarm Control Bits +#define ALMPOL 7 // Alarm Polarity: Defines the logic level for the MFP when an alarm is triggered. +#define ALMC2 6 // Alarm configuration bits determine how alarms match. See ALM_MATCH defines below. +#define ALMC1 5 +#define ALMC0 4 +#define ALMIF 3 // Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. + +// Constructor. Initializes the I2C bus by default, but better +// practice is to pass false in the constructor and call +// the begin() function in the setup code. +MCP79412RTC::MCP79412RTC(bool initI2C) +{ + if (initI2C) i2cBegin(); +} + +// Initialize the I2C bus. +void MCP79412RTC::begin() { i2cBegin(); } -/*----------------------------------------------------------------------* - * Read the current time from the RTC and return it as a time_t value. * - * Returns a zero value if RTC not present (I2C I/O error). * - *----------------------------------------------------------------------*/ -time_t MCP79412RTC::get(void) +// Read the current time from the RTC and return it as a time_t value. +// Returns a zero value if RTC not present (I2C I/O error). +time_t MCP79412RTC::get() { tmElements_t tm; @@ -72,9 +131,7 @@ time_t MCP79412RTC::get(void) return 0; } -/*----------------------------------------------------------------------* - * Set the RTC to the given time_t value. * - *----------------------------------------------------------------------*/ +// Set the RTC to the given time_t value. void MCP79412RTC::set(time_t t) { tmElements_t tm; @@ -83,11 +140,9 @@ void MCP79412RTC::set(time_t t) write(tm); } -/*----------------------------------------------------------------------* - * Read the current time from the RTC and return it in a tmElements_t * - * structure. Returns false if RTC not present (I2C I/O error). * - *----------------------------------------------------------------------*/ -boolean MCP79412RTC::read(tmElements_t &tm) +// Read the current time from the RTC and return it in a tmElements_t +// structure. Returns false if RTC not present (I2C I/O error). +bool MCP79412RTC::read(tmElements_t &tm) { i2cBeginTransmission(RTC_ADDR); i2cWrite((uint8_t)TIME_REG); @@ -95,30 +150,28 @@ boolean MCP79412RTC::read(tmElements_t &tm) return false; } else { - //request 7 bytes (secs, min, hr, dow, date, mth, yr) + // request 7 bytes (secs, min, hr, dow, date, mth, yr) i2cRequestFrom(RTC_ADDR, tmNbrFields); tm.Second = bcd2dec(i2cRead() & ~_BV(ST)); tm.Minute = bcd2dec(i2cRead()); - tm.Hour = bcd2dec(i2cRead() & ~_BV(HR1224)); //assumes 24hr clock - tm.Wday = i2cRead() & ~(_BV(OSCON) | _BV(VBAT) | _BV(VBATEN)); //mask off OSCON, VBAT, VBATEN bits + tm.Hour = bcd2dec(i2cRead() & ~_BV(HR1224)); // assumes 24hr clock + tm.Wday = i2cRead() & ~(_BV(OSCON) | _BV(VBAT) | _BV(VBATEN)); // mask off OSCON, VBAT, VBATEN bits tm.Day = bcd2dec(i2cRead()); - tm.Month = bcd2dec(i2cRead() & ~_BV(LP)); //mask off the leap year bit + tm.Month = bcd2dec(i2cRead() & ~_BV(LP)); // mask off the leap year bit tm.Year = y2kYearToTm(bcd2dec(i2cRead())); return true; } } -/*----------------------------------------------------------------------* - * Set the RTC's time from a tmElements_t structure. * - *----------------------------------------------------------------------*/ +// Set the RTC's time from a tmElements_t structure. void MCP79412RTC::write(tmElements_t &tm) { i2cBeginTransmission(RTC_ADDR); i2cWrite((uint8_t)TIME_REG); - i2cWrite((uint8_t)0x00); //stops the oscillator (Bit 7, ST == 0) + i2cWrite((uint8_t)0x00); // stops the oscillator (Bit 7, ST == 0) i2cWrite(dec2bcd(tm.Minute)); - i2cWrite(dec2bcd(tm.Hour)); //sets 24 hour format (Bit 6 == 0) - i2cWrite(tm.Wday | _BV(VBATEN)); //enable battery backup operation + i2cWrite(dec2bcd(tm.Hour)); // sets 24 hour format (Bit 6 == 0) + i2cWrite(tm.Wday | _BV(VBATEN)); // enable battery backup operation i2cWrite(dec2bcd(tm.Day)); i2cWrite(dec2bcd(tm.Month)); i2cWrite(dec2bcd(tmYearToY2k(tm.Year))); @@ -126,25 +179,21 @@ void MCP79412RTC::write(tmElements_t &tm) i2cBeginTransmission(RTC_ADDR); i2cWrite((uint8_t)TIME_REG); - i2cWrite(dec2bcd(tm.Second) | _BV(ST)); //set the seconds and start the oscillator (Bit 7, ST == 1) + i2cWrite(dec2bcd(tm.Second) | _BV(ST)); // set the seconds and start the oscillator (Bit 7, ST == 1) i2cEndTransmission(); } -/*----------------------------------------------------------------------* - * Write a single byte to RTC RAM. * - * Valid address range is 0x00 - 0x5F, no checking. * - *----------------------------------------------------------------------*/ +// Write a single byte to RTC RAM. +// Valid address range is 0x00 - 0x5F, no checking. void MCP79412RTC::ramWrite(byte addr, byte value) { ramWrite(addr, &value, 1); } -/*----------------------------------------------------------------------* - * Write multiple bytes to RTC RAM. * - * Valid address range is 0x00 - 0x5F, no checking. * - * Number of bytes (nBytes) must be between 1 and 31 (Wire library * - * limitation). * - *----------------------------------------------------------------------*/ +// Write multiple bytes to RTC RAM. +// Valid address range is 0x00 - 0x5F, no checking. +// Number of bytes (nBytes) must be between 1 and 31 (Wire library +// limitation). void MCP79412RTC::ramWrite(byte addr, byte *values, byte nBytes) { i2cBeginTransmission(RTC_ADDR); @@ -153,10 +202,8 @@ void MCP79412RTC::ramWrite(byte addr, byte *values, byte nBytes) i2cEndTransmission(); } -/*----------------------------------------------------------------------* - * Read a single byte from RTC RAM. * - * Valid address range is 0x00 - 0x5F, no checking. * - *----------------------------------------------------------------------*/ +// Read a single byte from RTC RAM. +// Valid address range is 0x00 - 0x5F, no checking. byte MCP79412RTC::ramRead(byte addr) { byte value; @@ -165,12 +212,10 @@ byte MCP79412RTC::ramRead(byte addr) return value; } -/*----------------------------------------------------------------------* - * Read multiple bytes from RTC RAM. * - * Valid address range is 0x00 - 0x5F, no checking. * - * Number of bytes (nBytes) must be between 1 and 32 (Wire library * - * limitation). * - *----------------------------------------------------------------------*/ +// Read multiple bytes from RTC RAM. +// Valid address range is 0x00 - 0x5F, no checking. +// Number of bytes (nBytes) must be between 1 and 32 (Wire library +// limitation). void MCP79412RTC::ramRead(byte addr, byte *values, byte nBytes) { i2cBeginTransmission(RTC_ADDR); @@ -180,24 +225,20 @@ void MCP79412RTC::ramRead(byte addr, byte *values, byte nBytes) for (byte i=0; i= 1 && nBytes <= EEPROM_PAGE_SIZE) { @@ -274,10 +307,8 @@ void MCP79412RTC::eepromWrite(byte addr, byte *values, byte nBytes) } } -/*----------------------------------------------------------------------* - * Read a single byte from EEPROM. * - * Address (addr) is constrained to the range (0, 127). * - *----------------------------------------------------------------------*/ +// Read a single byte from EEPROM. +// Address (addr) is constrained to the range (0, 127). byte MCP79412RTC::eepromRead(byte addr) { byte value; @@ -286,15 +317,13 @@ byte MCP79412RTC::eepromRead(byte addr) return value; } -/*----------------------------------------------------------------------* - * Read multiple bytes from EEPROM. * - * Address (addr) is constrained to the range (0, 127). * - * Number of bytes (nBytes) must be between 1 and 32 (Wire library * - * limitation). * - * Invalid values for addr or nBytes, or combinations of addr and * - * nBytes that would result in addressing past the last byte of EEPROM * - * result in no action. * - *----------------------------------------------------------------------*/ +// Read multiple bytes from EEPROM. +// Address (addr) is constrained to the range (0, 127). +// Number of bytes (nBytes) must be between 1 and 32 (Wire library +// limitation). +// Invalid values for addr or nBytes, or combinations of addr and +// nBytes that would result in addressing past the last byte of EEPROM +// result in no action. void MCP79412RTC::eepromRead(byte addr, byte *values, byte nBytes) { #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) @@ -310,10 +339,8 @@ void MCP79412RTC::eepromRead(byte addr, byte *values, byte nBytes) } } -/*----------------------------------------------------------------------* - * Wait for EEPROM write to complete. * - *----------------------------------------------------------------------*/ -byte MCP79412RTC::eepromWait(void) +// Wait for EEPROM write to complete. +byte MCP79412RTC::eepromWait() { byte waitCount = 0; byte txStatus; @@ -330,13 +357,11 @@ byte MCP79412RTC::eepromWait(void) return waitCount; } -/*----------------------------------------------------------------------* - * Read the calibration register. * - * The calibration value is not a twos-complement number. The MSB is * - * the sign bit, and the 7 LSBs are an unsigned number, so we convert * - * it and return it to the caller as a regular twos-complement integer. * - *----------------------------------------------------------------------*/ -int MCP79412RTC::calibRead(void) +// Read the calibration register. +// The calibration value is not a twos-complement number. The MSB is +// the sign bit, and the 7 LSBs are an unsigned number, so we convert +// it and return it to the caller as a regular twos-complement integer. +int MCP79412RTC::calibRead() { byte val = ramRead(CALIB_REG); @@ -344,11 +369,9 @@ int MCP79412RTC::calibRead(void) else return val; } -/*----------------------------------------------------------------------* - * Write the calibration register. * - * Calibration value must be between -127 and 127, others result * - * in no action. See note above on the format of the calibration value. * - *----------------------------------------------------------------------*/ +// Write the calibration register. +// Calibration value must be between -127 and 127, others result +// in no action. See note above on the format of the calibration value. void MCP79412RTC::calibWrite(int value) { byte calibVal; @@ -360,11 +383,9 @@ void MCP79412RTC::calibWrite(int value) } } -/*----------------------------------------------------------------------* - * Read the unique ID. * - * For the MCP79411 (EUI-48), the first two bytes will contain 0xFF. * - * Caller must provide an 8-byte array to contain the results. * - *----------------------------------------------------------------------*/ +// Read the unique ID. +// For the MCP79411 (EUI-48), the first two bytes will contain 0xFF. +// Caller must provide an 8-byte array to contain the results. void MCP79412RTC::idRead(byte *uniqueID) { i2cBeginTransmission(EEPROM_ADDR); @@ -374,13 +395,11 @@ void MCP79412RTC::idRead(byte *uniqueID) for (byte i=0; i *powerUp) { --dn.Year; *powerDown = makeTime(dn); @@ -469,9 +486,7 @@ boolean MCP79412RTC::powerFail(time_t *powerDown, time_t *powerUp) return false; } -/*----------------------------------------------------------------------* - * Enable or disable the square wave output. * - *----------------------------------------------------------------------*/ +// Enable or disable the square wave output. void MCP79412RTC::squareWave(uint8_t freq) { uint8_t ctrlReg; @@ -486,65 +501,59 @@ void MCP79412RTC::squareWave(uint8_t freq) ramWrite(CTRL_REG, &ctrlReg, 1); } -/*----------------------------------------------------------------------* - * Set an alarm time. Sets the alarm registers only, does not enable * - * the alarm. See enableAlarm(). * - *----------------------------------------------------------------------*/ +// Set an alarm time. Sets the alarm registers only, does not enable +// the alarm. See enableAlarm(). void MCP79412RTC::setAlarm(uint8_t alarmNumber, time_t alarmTime) { tmElements_t tm; - uint8_t day; //need to preserve bits in the day (of week) register + uint8_t day; // need to preserve bits in the day (of week) register - alarmNumber &= 0x01; //ensure a valid alarm number + alarmNumber &= 0x01; // ensure a valid alarm number ramRead( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG) , &day, 1); breakTime(alarmTime, tm); i2cBeginTransmission(RTC_ADDR); i2cWrite( ALM0_REG + alarmNumber * (ALM1_REG - ALM0_REG) ); i2cWrite(dec2bcd(tm.Second)); i2cWrite(dec2bcd(tm.Minute)); - i2cWrite(dec2bcd(tm.Hour)); //sets 24 hour format (Bit 6 == 0) + i2cWrite(dec2bcd(tm.Hour)); // sets 24 hour format (Bit 6 == 0) i2cWrite( (day & 0xF8) + tm.Wday ); i2cWrite(dec2bcd(tm.Day)); i2cWrite(dec2bcd(tm.Month)); i2cEndTransmission(); } -/*----------------------------------------------------------------------* - * Enable or disable an alarm, and set the trigger criteria, * - * e.g. match only seconds, only minutes, entire time and date, etc. * - *----------------------------------------------------------------------*/ +// Enable or disable an alarm, and set the trigger criteria, +// e.g. match only seconds, only minutes, entire time and date, etc. void MCP79412RTC::enableAlarm(uint8_t alarmNumber, uint8_t alarmType) { - uint8_t day; //alarm day register has config & flag bits - uint8_t ctrl; //control register has alarm enable bits + uint8_t day; // alarm day register has config & flag bits + uint8_t ctrl; // control register has alarm enable bits - alarmNumber &= 0x01; //ensure a valid alarm number + alarmNumber &= 0x01; // ensure a valid alarm number ramRead(CTRL_REG, &ctrl, 1); if (alarmType < ALM_DISABLE) { ramRead(ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); - day = ( day & 0x87 ) | alarmType << 4; //reset interrupt flag, OR in the config bits + day = ( day & 0x87 ) | alarmType << 4; // reset interrupt flag, OR in the config bits ramWrite(ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); - ctrl |= _BV(ALM0 + alarmNumber); //enable the alarm + ctrl |= _BV(ALM0 + alarmNumber); // enable the alarm } else { - ctrl &= ~(_BV(ALM0 + alarmNumber)); //disable the alarm + ctrl &= ~(_BV(ALM0 + alarmNumber)); // disable the alarm } ramWrite(CTRL_REG, &ctrl, 1); } -/*----------------------------------------------------------------------* - * Returns true or false depending on whether the given alarm has been * - * triggered, and resets the alarm "interrupt" flag. This is not a real * - * interrupt, just a bit that's set when an alarm is triggered. * - *----------------------------------------------------------------------*/ -boolean MCP79412RTC::alarm(uint8_t alarmNumber) +// Returns true or false depending on whether the given alarm has been +// triggered, and resets the alarm "interrupt" flag. This is not a real +// interrupt, just a bit that's set when an alarm is triggered. +bool MCP79412RTC::alarm(uint8_t alarmNumber) { - uint8_t day; //alarm day register has config & flag bits + uint8_t day; // alarm day register has config & flag bits - alarmNumber &= 0x01; //ensure a valid alarm number + alarmNumber &= 0x01; // ensure a valid alarm number ramRead( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); if (day & _BV(ALMIF)) { - day &= ~_BV(ALMIF); //turn off the alarm "interrupt" flag + day &= ~_BV(ALMIF); // turn off the alarm "interrupt" flag ramWrite( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); return true; } @@ -552,11 +561,9 @@ boolean MCP79412RTC::alarm(uint8_t alarmNumber) return false; } -/*----------------------------------------------------------------------* - * Sets the logic level on the MFP when it's not being used as a * - * square wave or alarm output. The default is HIGH. * - *----------------------------------------------------------------------*/ -void MCP79412RTC::out(boolean level) +// Sets the logic level on the MFP when it's not being used as a +// square wave or alarm output. The default is HIGH. +void MCP79412RTC::out(bool level) { uint8_t ctrlReg; @@ -568,19 +575,17 @@ void MCP79412RTC::out(boolean level) ramWrite(CTRL_REG, &ctrlReg, 1); } -/*----------------------------------------------------------------------* - * Specifies 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 alarm * - * "interrupt" flags, and the alarm() function will indicate when an * - * alarm is triggered regardless of the polarity. * - *----------------------------------------------------------------------*/ -void MCP79412RTC::alarmPolarity(boolean polarity) +// Specifies 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 alarm +// "interrupt" flags, and the alarm() function will indicate when an +// alarm is triggered regardless of the polarity. +void MCP79412RTC::alarmPolarity(bool polarity) { uint8_t alm0Day; @@ -592,27 +597,23 @@ void MCP79412RTC::alarmPolarity(boolean polarity) ramWrite(ALM0_DAY, &alm0Day, 1); } -/*----------------------------------------------------------------------* - * Check to see if the RTC's oscillator is started (ST bit in seconds * - * register). Returns true if started. * - *----------------------------------------------------------------------*/ -boolean MCP79412RTC::isRunning(void) +// Check to see if the RTC's oscillator is started (ST bit in seconds +// register). Returns true if started. +bool MCP79412RTC::isRunning() { i2cBeginTransmission(RTC_ADDR); i2cWrite((uint8_t)TIME_REG); i2cEndTransmission(); - //request just the seconds register + // request just the seconds register i2cRequestFrom(RTC_ADDR, 1); return i2cRead() & _BV(ST); } -/*----------------------------------------------------------------------* - * 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. * - *----------------------------------------------------------------------*/ -void MCP79412RTC::vbaten(boolean enable) +// 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. +void MCP79412RTC::vbaten(bool enable) { uint8_t day; @@ -626,21 +627,18 @@ void MCP79412RTC::vbaten(boolean enable) return; } -/*----------------------------------------------------------------------* - * Decimal-to-BCD conversion * - *----------------------------------------------------------------------*/ +// Decimal-to-BCD conversion uint8_t MCP79412RTC::dec2bcd(uint8_t n) { return n + 6 * (n / 10); } -/*----------------------------------------------------------------------* - * BCD-to-Decimal conversion * - *----------------------------------------------------------------------*/ +// BCD-to-Decimal conversion uint8_t __attribute__ ((noinline)) MCP79412RTC::bcd2dec(uint8_t n) { return n - 6 * (n >> 4); } -MCP79412RTC RTC = MCP79412RTC(); //instantiate an RTC object - +#if defined ARDUINO_ARCH_AVR +MCP79412RTC RTC; // instantiate an RTC object for AVR only +#endif diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index edee9ad..f552392 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -1,99 +1,61 @@ -/*----------------------------------------------------------------------* - * MCP79412RTC.h - Arduino library for the Microchip MCP7941x * - * Real-Time Clocks. This library is intended for use with the Arduino * - * Time.h library, http://www.arduino.cc/playground/Code/Time * - * * - * This library is a drop-in replacement for the DS1307RTC.h library * - * by Michael Margolis that is supplied with the Arduino Time library * - * above. To change from using a DS1307 RTC to an MCP7941x RTC, it is * - * only necessary to change the #include statement to include this * - * library instead of DS1307RTC.h. * - * * - * In addition, this library implements functions to support the * - * additional features of the MCP7941x. * - * * - * Jack Christensen 29Jul2012 * - * * - * This work is licensed under the Creative Commons Attribution- * - * ShareAlike 3.0 Unported License. To view a copy of this license, * - * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * - * letter to Creative Commons, 171 Second Street, Suite 300, * - * San Francisco, California, 94105, USA. * - *----------------------------------------------------------------------*/ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Arduino library for the Microchip MCP7941x Real-Time Clocks. +// Requires PJRC's improved version of the Arduino Time Library, +// https://playground.arduino.cc/Code/Time +// https://github.com/PaulStoffregen/Time +// +// For AVR architecture, an MCP79412RTC object named RTC is instantiated +// by the library and I2C initialization occurs in the constructor; +// this is for backwards compatibility. +// For other architectures, the user needs to instantiate a MCP79412RTC +// object and optionally initialize the I2C bus by calling +// MCP79412RTC::begin(). The constructor has an optional bool parameter +// to indicate whether I2C initialization should occur in the +// constructor; this parameter defaults to true if not given. -#ifndef MCP79412RTC_h -#define MCP79412RTC_h -#include +#ifndef MCP79412RTC_H_INCLUDED +#define MCP79412RTC_H_INCLUDED -#if defined(ARDUINO) && ARDUINO >= 100 -#include -#else -#include -#endif - -//MCP7941x I2C Addresses -#define RTC_ADDR 0x6F -#define EEPROM_ADDR 0x57 - -//MCP7941x Register Addresses -#define TIME_REG 0x00 //7 registers, Seconds, Minutes, Hours, DOW, Date, Month, Year -#define DAY_REG 0x03 //the RTC Day register contains the OSCON, VBAT, and VBATEN bits -#define YEAR_REG 0x06 //RTC year register -#define CTRL_REG 0x07 //control register -#define CALIB_REG 0x08 //calibration register -#define UNLOCK_ID_REG 0x09 //unlock ID register -#define ALM0_REG 0x0A //alarm 0, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month -#define ALM1_REG 0x11 //alarm 1, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month -#define ALM0_DAY 0x0D //DOW register has alarm config/flag bits -#define PWRDWN_TS_REG 0x18 //power-down timestamp, 4 registers, Minutes, Hours, Date, Month -#define PWRUP_TS_REG 0x1C //power-up timestamp, 4 registers, Minutes, Hours, Date, Month -#define TIMESTAMP_SIZE 8 //number of bytes in the two timestamp registers -#define SRAM_START_ADDR 0x20 //first SRAM address -#define SRAM_SIZE 64 //number of bytes of SRAM -#define EEPROM_SIZE 128 //number of bytes of EEPROM -#define EEPROM_PAGE_SIZE 8 //number of bytes on an EEPROM page -#define UNIQUE_ID_ADDR 0xF0 //starting address for unique ID -#define UNIQUE_ID_SIZE 8 //number of bytes in unique ID +#include -//Control Register bits -#define OUT 7 //sets logic level on MFP when not used as square wave output -#define SQWE 6 //set to enable square wave output -#define ALM1 5 //alarm 1 is active -#define ALM0 4 //alarm 0 is active -#define EXTOSC 3 //set to drive the RTC registers from an external oscillator instead of a crystal -#define RS2 2 //RS2:0 set square wave output frequency: 0==1Hz, 1==4096Hz, 2==8192Hz, 3=32768Hz -#define RS1 1 -#define RS0 0 -enum {SQWAVE_1_HZ, SQWAVE_4096_HZ, SQWAVE_8192_HZ, SQWAVE_32768_HZ, SQWAVE_NONE}; +// Alarm types for use with the enableAlarm() function +enum { + ALM_MATCH_SECONDS, + ALM_MATCH_MINUTES, + ALM_MATCH_HOURS, + ALM_MATCH_DAY, // triggers alarm at midnight + ALM_MATCH_DATE, + ALM_RESERVED_5, // do not use + ALM_RESERVED_6, // do not use + ALM_MATCH_DATETIME, + ALM_DISABLE +}; -//Other Control Bits -#define ST 7 //Seconds register (TIME_REG) oscillator start/stop bit, 1==Start, 0==Stop -#define HR1224 6 //Hours register (TIME_REG+2) 12 or 24 hour mode (24 hour mode==0) -#define AMPM 5 //Hours register (TIME_REG+2) AM/PM bit for 12 hour mode -#define OSCON 5 //Day register (TIME_REG+3) oscillator running (set and cleared by hardware) -#define VBAT 4 //Day register (TIME_REG+3) set by hardware when Vcc fails and RTC runs on battery. - //VBAT is cleared by software, clearing VBAT also clears the timestamp registers -#define VBATEN 3 //Day register (TIME_REG+3) VBATEN==1 enables backup battery, VBATEN==0 disconnects the VBAT pin (e.g. to save battery) -#define LP 5 //Month register (TIME_REG+5) leap year bit +// Square-wave output frequencies for use with squareWave() function +enum { + SQWAVE_1_HZ, + SQWAVE_4096_HZ, + SQWAVE_8192_HZ, + SQWAVE_32768_HZ, + SQWAVE_NONE +}; -//Alarm Control Bits -#define ALMPOL 7 //Alarm Polarity: Defines the logic level for the MFP when an alarm is triggered. -#define ALMC2 6 //Alarm configuration bits determine how alarms match. See ALM_MATCH defines below. -#define ALMC1 5 -#define ALMC0 4 -#define ALMIF 3 //Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. -enum {ALM_MATCH_SECONDS, ALM_MATCH_MINUTES, ALM_MATCH_HOURS, ALM_MATCH_DAY, ALM_MATCH_DATE, ALM_RESERVED_5, ALM_RESERVED_6, ALM_MATCH_DATETIME, ALM_DISABLE}; -//Note ALM_MATCH_DAY triggers alarm at midnight -#define ALARM_0 0 //constants for calling functions +// constants for use with alarm functions +#define ALARM_0 0 #define ALARM_1 1 class MCP79412RTC { public: - MCP79412RTC(); - static time_t get(void); + MCP79412RTC(bool initI2C = true); + void begin(); + static time_t get(); static void set(time_t t); - static boolean read(tmElements_t &tm); + static bool read(tmElements_t &tm); static void write(tmElements_t &tm); void sramWrite(byte addr, byte value); void sramWrite(byte addr, byte *values, byte nBytes); @@ -103,31 +65,40 @@ class MCP79412RTC void eepromWrite(byte addr, byte *values, byte nBytes); byte eepromRead(byte addr); void eepromRead(byte addr, byte *values, byte nBytes); - int calibRead(void); + int calibRead(); void calibWrite(int value); void idRead(byte *uniqueID); void getEUI64(byte *uniqueID); - boolean powerFail(time_t *powerDown, time_t *powerUp); + bool powerFail(time_t *powerDown, time_t *powerUp); void squareWave(uint8_t freq); void setAlarm(uint8_t alarmNumber, time_t alarmTime); void enableAlarm(uint8_t alarmNumber, uint8_t alarmType); - boolean alarm(uint8_t alarmNumber); - void out(boolean level); - void alarmPolarity(boolean polarity); - boolean isRunning(void); - void vbaten(boolean enable); + bool alarm(uint8_t alarmNumber); + void out(bool level); + void alarmPolarity(bool polarity); + bool isRunning(); + void vbaten(bool enable); private: static void ramWrite(byte addr, byte value); static void ramWrite(byte addr, byte *values, byte nBytes); static byte ramRead(byte addr); static void ramRead(byte addr, byte *values, byte nBytes); - static byte eepromWait(void); + static byte eepromWait(); static uint8_t dec2bcd(uint8_t num); static uint8_t bcd2dec(uint8_t num); }; +#if defined ARDUINO_ARCH_AVR extern MCP79412RTC RTC; +#endif + +#ifndef _BV +#define _BV(bit) (1 << (bit)) +#endif +#ifndef BUFFER_LENGTH // a horrible and limiting kludge for samd (arduino zero) +#define BUFFER_LENGTH 32 #endif +#endif From d80a88eb6e555a4ab83d7590c1e3cad2169eb9d2 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 7 Apr 2018 17:47:02 -0400 Subject: [PATCH 07/22] Update keywords.txt file. --- keywords.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/keywords.txt b/keywords.txt index eb42a60..b250cde 100644 --- a/keywords.txt +++ b/keywords.txt @@ -1,4 +1,5 @@ MCP79412RTC KEYWORD1 +begin KEYWORD2 get KEYWORD2 set KEYWORD2 read KEYWORD2 @@ -10,6 +11,7 @@ eepromRead KEYWORD2 calibRead KEYWORD2 calibWrite KEYWORD2 idRead KEYWORD2 +getEUI64 KEYWORD2 powerFail KEYWORD2 squareWave KEYWORD2 setAlarm KEYWORD2 @@ -18,3 +20,4 @@ alarm KEYWORD2 out KEYWORD2 alarmPolarity KEYWORD2 isRunning KEYWORD2 +vbaten KEYWORD2 From edc6ce4d0c1c06e3fe44e039a4ad475414454341 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sun, 8 Apr 2018 09:09:16 -0400 Subject: [PATCH 08/22] Rearrange #includes. --- src/MCP79412RTC.cpp | 22 +++------------------- src/MCP79412RTC.h | 3 ++- 2 files changed, 5 insertions(+), 20 deletions(-) diff --git a/src/MCP79412RTC.cpp b/src/MCP79412RTC.cpp index 9a72b11..76ff0bf 100644 --- a/src/MCP79412RTC.cpp +++ b/src/MCP79412RTC.cpp @@ -17,13 +17,9 @@ // to indicate whether I2C initialization should occur in the // constructor; this parameter defaults to true if not given. -#if defined(ARDUINO) && ARDUINO >= 100 -#include -#else -#include -#endif +#include -// release-independent I2C functions +// define consistent I2C functions #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) #include #define i2cBegin TinyWireM.begin @@ -32,7 +28,7 @@ #define i2cRequestFrom TinyWireM.requestFrom #define i2cRead TinyWireM.receive #define i2cWrite TinyWireM.send -#elif ARDUINO >= 100 +#else #include #define i2cBegin Wire.begin #define i2cBeginTransmission Wire.beginTransmission @@ -40,20 +36,8 @@ #define i2cRequestFrom Wire.requestFrom #define i2cRead Wire.read #define i2cWrite Wire.write -#else -#include -#define i2cBegin Wire.begin -#define i2cBeginTransmission Wire.beginTransmission -#define i2cEndTransmission Wire.endTransmission -#define i2cRequestFrom Wire.requestFrom -#define i2cRead Wire.receive -#define i2cWrite Wire.send #endif -#include -#include // https://github.com/PaulStoffregen/Time - - // MCP7941x I2C Addresses #define RTC_ADDR 0x6F #define EEPROM_ADDR 0x57 diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index f552392..a32e620 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -20,7 +20,8 @@ #ifndef MCP79412RTC_H_INCLUDED #define MCP79412RTC_H_INCLUDED -#include +#include +#include // https://github.com/PaulStoffregen/Time // Alarm types for use with the enableAlarm() function enum { From 4cd43f1710c148e80cc0f3e5649c85f02f07aeb3 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Fri, 11 Oct 2019 17:41:19 -0400 Subject: [PATCH 09/22] Example sketch bug fix. --- examples/rtcSetSerial/rtcSetSerial.ino | 32 ++++++++++++++------------ 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/examples/rtcSetSerial/rtcSetSerial.ino b/examples/rtcSetSerial/rtcSetSerial.ino index e5ca204..0512286 100644 --- a/examples/rtcSetSerial/rtcSetSerial.ino +++ b/examples/rtcSetSerial/rtcSetSerial.ino @@ -10,7 +10,7 @@ #include // https://github.com/JChristensen/MCP79412RTC #include // https://github.com/PaulStoffregen/Time -const uint32_t PRINT_INTERVAL(1000); // ms between printing the time +const uint32_t PRINT_INTERVAL(10000); // ms between printing the time uint32_t ms, msLast; void setup() @@ -40,24 +40,25 @@ void loop() void readCommand() { char cmd[24] = "Set yyyy-mm-dd hh:mm:ss"; - static int i; - tmElements_t tmSet; - time_t tSet; - if (Serial.available() >= 23) { // enough characters for the whole command? - i = 0; // yes, read the available characters + // serial terminal will send 23 char command plus line terminator (0x0A) + if (Serial.available() >= 24) { // enough characters for the whole command? + unsigned int i = 0; // yes, read the available characters while (Serial.available() > 0) { - if (i >= sizeof(cmd) - 1) { // more than we can enjoy - flushInput(); // clear out the input buffer + if (i >= sizeof(cmd)) { // more than we can enjoy + flushInput(); // clear out the input buffer + cmd[sizeof(cmd) - 1] = 0; // string terminator Serial.print("Too long: "); Serial.println(cmd); return; } - delay(2); //let the next character trickle in - cmd[i++] = char(Serial.read()); + delay(2); // let the next character trickle in + char c = Serial.read(); + if (c >= ' ') cmd[i++] = c; // printable characters and spaces only } - cmd[i] = 0; //put in string terminator + cmd[i] = 0; // put in string terminator + tmElements_t tmSet; if (strncmp(cmd, "Set ", 4) == 0) { tmSet.Year = 1000 * (cmd[4] - '0') + 100 * (cmd[5] - '0') + 10 * (cmd[6] - '0') + cmd[7] - '0' - 1970; tmSet.Month = 10 * (cmd[9] - '0') + cmd[10] - '0'; @@ -65,11 +66,12 @@ void readCommand() tmSet.Hour = 10 * (cmd[15] - '0') + cmd[16] - '0'; tmSet.Minute = 10 * (cmd[18] - '0') + cmd[19] - '0'; tmSet.Second = 10 * (cmd[21] - '0') + cmd[22] - '0'; - tSet = makeTime(tmSet); // convert to time_t - setTime(tSet); // set the system time - RTC.set(now()); // set the rtc + time_t tSet = makeTime(tmSet); // convert to time_t + setTime(tSet); // set the system time + RTC.set(now()); // set the rtc Serial.println("RTC set!"); - flushInput(); // discard any extraneous trailing characters + printTime(RTC.get()); + flushInput(); // discard any extraneous trailing characters } else { Serial.print("Unknown: "); From 24970f2a1e5c26f66a61c98473a38ae2251ea1cc Mon Sep 17 00:00:00 2001 From: JChristensen Date: Mon, 30 Dec 2019 21:12:03 -0500 Subject: [PATCH 10/22] Add depends to library.properties. Closes #5. Fix compiler warnings in example sketches. --- examples/PowerOutageLogger/PowerOutageLogger.ino | 2 +- examples/rtcSet3/rtcSet3.ino | 3 +-- library.properties | 3 ++- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/PowerOutageLogger/PowerOutageLogger.ino b/examples/PowerOutageLogger/PowerOutageLogger.ino index a2e925d..52eb24d 100644 --- a/examples/PowerOutageLogger/PowerOutageLogger.ino +++ b/examples/PowerOutageLogger/PowerOutageLogger.ino @@ -167,7 +167,7 @@ time_t read32(uint8_t addr) } // Print time with time zone -void printTime(time_t t, char *tz) +void printTime(time_t t, const char *tz) { sPrintI00(hour(t)); sPrintDigits(minute(t)); diff --git a/examples/rtcSet3/rtcSet3.ino b/examples/rtcSet3/rtcSet3.ino index d9f6446..5e5b61f 100644 --- a/examples/rtcSet3/rtcSet3.ino +++ b/examples/rtcSet3/rtcSet3.ino @@ -30,9 +30,8 @@ void loop() time_t compileTime() { const uint32_t FUDGE(15); // fudge factor to allow for compile time (seconds, YMMV) - char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec"; + const char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec"; char chMon[3], *m; - int d, y; tmElements_t tm; time_t t; diff --git a/library.properties b/library.properties index 10a07c1..274e7b4 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=MCP79412RTC -version=1.1.0 +version=1.0.2 author=Jack Christensen maintainer=Jack Christensen sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. @@ -7,3 +7,4 @@ paragraph=Requires PJRC's improved Arduino Time Library, https://github.com/Paul category=Timing url=https://github.com/JChristensen/MCP79412RTC architectures=avr +depends=Time From 15a3a0fe031d8bf56390e2c33f481fc172c984e2 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Tue, 26 Apr 2022 17:34:30 -0400 Subject: [PATCH 11/22] Initial commit for v2.0.0. Move enums inside class scope. Replace #defines for registers and bits with constexpr and move inside class scope. Add enum for alarm number, ALARM_NBR_t. Add methods to dump timekeeping registers, SRAM and EEPROM. Remove definition of "RTC" object. User must define their own. Change to fixed-width integer data types. --- .gitignore | 2 +- examples/SetSerial/SetSerial.ino | 76 +++----- src/MCP79412RTC.cpp | 315 ++++++++++++++++--------------- src/MCP79412RTC.h | 191 +++++++++++++------ 4 files changed, 330 insertions(+), 254 deletions(-) diff --git a/.gitignore b/.gitignore index 484b17a..8cb3738 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -ReadMe.txt +ReadMe.txt diff --git a/examples/SetSerial/SetSerial.ino b/examples/SetSerial/SetSerial.ino index 7b6707e..7b0c617 100644 --- a/examples/SetSerial/SetSerial.ino +++ b/examples/SetSerial/SetSerial.ino @@ -34,20 +34,24 @@ #include // http://arduiniana.org/libraries/streaming/ #include // https://github.com/PaulStoffregen/Time +MCP79412RTC myRTC; + void setup() { - byte rtcID[8]; - Serial.begin(115200); + Serial << F( "\n" __FILE__ "\n" __DATE__ " " __TIME__ "\n" ); + myRTC.begin(); + myRTC.dumpRegs(); // setSyncProvider() causes the Time library to synchronize with the - // external RTC by calling RTC.get() every five minutes by default. - setSyncProvider(RTC.get); + // external RTC by calling myRTC.get() every five minutes by default. + setSyncProvider(myRTC.get); Serial << endl << F("RTC Sync"); if (timeStatus() != timeSet) Serial << F(" FAIL!"); Serial << endl; - RTC.idRead(rtcID); + uint8_t rtcID[8]; + myRTC.idRead(rtcID); Serial << F("RTC ID = "); for (int i=0; i<8; ++i) { if (rtcID[i] < 16) Serial << '0'; @@ -55,7 +59,7 @@ void setup() } Serial << endl; - RTC.getEUI64(rtcID); + myRTC.getEUI64(rtcID); Serial << F("EUI-64 = "); for (int i=0; i<8; ++i) { if (rtcID[i] < 16) Serial << '0'; @@ -63,13 +67,11 @@ void setup() } Serial << endl; - Serial << F("Calibration Register = ") << RTC.calibRead() << endl; + Serial << F("Calibration Register = ") << myRTC.calibRead() << endl; } void loop() { - static time_t tLast; - time_t t; tmElements_t tm; int cmdChar, y, oldCal, newCal; @@ -96,11 +98,11 @@ void loop() tm.Hour = Serial.parseInt(); tm.Minute = Serial.parseInt(); tm.Second = Serial.parseInt(); - t = makeTime(tm); - RTC.set(t); // use the time_t value to ensure correct weekday is set + time_t t = makeTime(tm); + myRTC.set(t); // use the time_t value to ensure correct weekday is set setTime(t); Serial << F("RTC set to: "); - printDateTime(t); + printTime(t); Serial << endl; } break; @@ -108,9 +110,9 @@ void loop() case 'C': case 'c': newCal = Serial.parseInt(); - oldCal = RTC.calibRead(); - RTC.calibWrite(newCal); - Serial << F("Calibration changed from ") << oldCal << F(" to ") << RTC.calibRead() << endl; + oldCal = myRTC.calibRead(); + myRTC.calibWrite(newCal); + Serial << F("Calibration changed from ") << oldCal << F(" to ") << myRTC.calibRead() << endl; break; default: @@ -122,44 +124,22 @@ void loop() while (Serial.available() > 0) Serial.read(); } - t = now(); + // print time and date every second + static time_t tLast; + time_t t { now() }; if (t != tLast) { tLast = t; - printDateTime(t); - Serial << endl; + printTime(t); } } -// print date and time to Serial -void printDateTime(time_t t) -{ - printDate(t); - Serial << ' '; - printTime(t); -} - -// print time to Serial +// format and print a time_t value void printTime(time_t t) { - printI00(hour(t), ':'); - printI00(minute(t), ':'); - printI00(second(t), ' '); -} - -// print date to Serial -void printDate(time_t t) -{ - printI00(day(t), 0); - Serial << monthShortStr(month(t)) << _DEC(year(t)); -} - -// Print an integer in "00" format (with leading zero), -// followed by a delimiter character to Serial. -// Input value assumed to be between 0 and 99. -void printI00(int val, char delim) -{ - if (val < 10) Serial << '0'; - Serial << _DEC(val); - if (delim > 0) Serial << delim; - return; + char buf[25]; + char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer) + strcpy(m, monthShortStr(month(t))); + sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d", + hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t)); + Serial.println(buf); } diff --git a/src/MCP79412RTC.cpp b/src/MCP79412RTC.cpp index 76ff0bf..701116d 100644 --- a/src/MCP79412RTC.cpp +++ b/src/MCP79412RTC.cpp @@ -19,84 +19,6 @@ #include -// define consistent I2C functions -#if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) -#include -#define i2cBegin TinyWireM.begin -#define i2cBeginTransmission TinyWireM.beginTransmission -#define i2cEndTransmission TinyWireM.endTransmission -#define i2cRequestFrom TinyWireM.requestFrom -#define i2cRead TinyWireM.receive -#define i2cWrite TinyWireM.send -#else -#include -#define i2cBegin Wire.begin -#define i2cBeginTransmission Wire.beginTransmission -#define i2cEndTransmission Wire.endTransmission -#define i2cRequestFrom Wire.requestFrom -#define i2cRead Wire.read -#define i2cWrite Wire.write -#endif - -// MCP7941x I2C Addresses -#define RTC_ADDR 0x6F -#define EEPROM_ADDR 0x57 - -// MCP7941x Register Addresses -#define TIME_REG 0x00 // 7 registers, Seconds, Minutes, Hours, DOW, Date, Month, Year -#define DAY_REG 0x03 // the RTC Day register contains the OSCON, VBAT, and VBATEN bits -#define YEAR_REG 0x06 // RTC year register -#define CTRL_REG 0x07 // control register -#define CALIB_REG 0x08 // calibration register -#define UNLOCK_ID_REG 0x09 // unlock ID register -#define ALM0_REG 0x0A // alarm 0, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month -#define ALM1_REG 0x11 // alarm 1, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month -#define ALM0_DAY 0x0D // DOW register has alarm config/flag bits -#define PWRDWN_TS_REG 0x18 // power-down timestamp, 4 registers, Minutes, Hours, Date, Month -#define PWRUP_TS_REG 0x1C // power-up timestamp, 4 registers, Minutes, Hours, Date, Month -#define TIMESTAMP_SIZE 8 // number of bytes in the two timestamp registers -#define SRAM_START_ADDR 0x20 // first SRAM address -#define SRAM_SIZE 64 // number of bytes of SRAM -#define EEPROM_SIZE 128 // number of bytes of EEPROM -#define EEPROM_PAGE_SIZE 8 // number of bytes on an EEPROM page -#define UNIQUE_ID_ADDR 0xF0 // starting address for unique ID -#define UNIQUE_ID_SIZE 8 // number of bytes in unique ID - -// Control Register bits -#define OUT 7 // sets logic level on MFP when not used as square wave output -#define SQWE 6 // set to enable square wave output -#define ALM1 5 // alarm 1 is active -#define ALM0 4 // alarm 0 is active -#define EXTOSC 3 // set to drive the RTC registers from an external oscillator instead of a crystal -#define RS2 2 // RS2:0 set square wave output frequency: 0==1Hz, 1==4096Hz, 2==8192Hz, 3=32768Hz -#define RS1 1 -#define RS0 0 - -// Other Control Bits -#define ST 7 // Seconds register (TIME_REG) oscillator start/stop bit, 1==Start, 0==Stop -#define HR1224 6 // Hours register (TIME_REG+2) 12 or 24 hour mode (24 hour mode==0) -#define AMPM 5 // Hours register (TIME_REG+2) AM/PM bit for 12 hour mode -#define OSCON 5 // Day register (TIME_REG+3) oscillator running (set and cleared by hardware) -#define VBAT 4 // Day register (TIME_REG+3) set by hardware when Vcc fails and RTC runs on battery. - // VBAT is cleared by software, clearing VBAT also clears the timestamp registers -#define VBATEN 3 // Day register (TIME_REG+3) VBATEN==1 enables backup battery, VBATEN==0 disconnects the VBAT pin (e.g. to save battery) -#define LP 5 // Month register (TIME_REG+5) leap year bit - -// Alarm Control Bits -#define ALMPOL 7 // Alarm Polarity: Defines the logic level for the MFP when an alarm is triggered. -#define ALMC2 6 // Alarm configuration bits determine how alarms match. See ALM_MATCH defines below. -#define ALMC1 5 -#define ALMC0 4 -#define ALMIF 3 // Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. - -// Constructor. Initializes the I2C bus by default, but better -// practice is to pass false in the constructor and call -// the begin() function in the setup code. -MCP79412RTC::MCP79412RTC(bool initI2C) -{ - if (initI2C) i2cBegin(); -} - // Initialize the I2C bus. void MCP79412RTC::begin() { @@ -129,13 +51,13 @@ void MCP79412RTC::set(time_t t) bool MCP79412RTC::read(tmElements_t &tm) { i2cBeginTransmission(RTC_ADDR); - i2cWrite((uint8_t)TIME_REG); + i2cWrite(TIME_REG); if (i2cEndTransmission() != 0) { return false; } else { // request 7 bytes (secs, min, hr, dow, date, mth, yr) - i2cRequestFrom(RTC_ADDR, tmNbrFields); + i2cRequestFrom(RTC_ADDR, static_cast(tmNbrFields)); tm.Second = bcd2dec(i2cRead() & ~_BV(ST)); tm.Minute = bcd2dec(i2cRead()); tm.Hour = bcd2dec(i2cRead() & ~_BV(HR1224)); // assumes 24hr clock @@ -151,25 +73,25 @@ bool MCP79412RTC::read(tmElements_t &tm) void MCP79412RTC::write(tmElements_t &tm) { i2cBeginTransmission(RTC_ADDR); - i2cWrite((uint8_t)TIME_REG); - i2cWrite((uint8_t)0x00); // stops the oscillator (Bit 7, ST == 0) + i2cWrite(TIME_REG); + i2cWrite(0x00); // stops the oscillator (Bit 7, ST == 0) i2cWrite(dec2bcd(tm.Minute)); - i2cWrite(dec2bcd(tm.Hour)); // sets 24 hour format (Bit 6 == 0) - i2cWrite(tm.Wday | _BV(VBATEN)); // enable battery backup operation + i2cWrite(dec2bcd(tm.Hour)); // sets 24 hour format (Bit 6 == 0) + i2cWrite(tm.Wday | _BV(VBATEN)); // enable battery backup operation i2cWrite(dec2bcd(tm.Day)); i2cWrite(dec2bcd(tm.Month)); i2cWrite(dec2bcd(tmYearToY2k(tm.Year))); i2cEndTransmission(); i2cBeginTransmission(RTC_ADDR); - i2cWrite((uint8_t)TIME_REG); - i2cWrite(dec2bcd(tm.Second) | _BV(ST)); // set the seconds and start the oscillator (Bit 7, ST == 1) + i2cWrite(TIME_REG); + i2cWrite(dec2bcd(tm.Second) | _BV(ST)); // set the seconds and start the oscillator (Bit 7, ST == 1) i2cEndTransmission(); } // Write a single byte to RTC RAM. // Valid address range is 0x00 - 0x5F, no checking. -void MCP79412RTC::ramWrite(byte addr, byte value) +void MCP79412RTC::ramWrite(uint8_t addr, uint8_t value) { ramWrite(addr, &value, 1); } @@ -178,19 +100,19 @@ void MCP79412RTC::ramWrite(byte addr, byte value) // Valid address range is 0x00 - 0x5F, no checking. // Number of bytes (nBytes) must be between 1 and 31 (Wire library // limitation). -void MCP79412RTC::ramWrite(byte addr, byte *values, byte nBytes) +void MCP79412RTC::ramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes) { i2cBeginTransmission(RTC_ADDR); i2cWrite(addr); - for (byte i=0; i= 1 && (addr + nBytes) <= SRAM_SIZE) { @@ -236,9 +158,9 @@ void MCP79412RTC::sramWrite(byte addr, byte *values, byte nBytes) // Read a single byte from Static RAM. // Address (addr) is constrained to the range (0, 63). -byte MCP79412RTC::sramRead(byte addr) +uint8_t MCP79412RTC::sramRead(uint8_t addr) { - byte value; + uint8_t value; ramRead( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, &value, 1 ); return value; @@ -251,7 +173,7 @@ byte MCP79412RTC::sramRead(byte addr) // Invalid values for nBytes, or combinations of addr and // nBytes that would result in addressing past the last byte of SRAM // result in no action. -void MCP79412RTC::sramRead(byte addr, byte *values, byte nBytes) +void MCP79412RTC::sramRead(uint8_t addr, uint8_t* values, uint8_t nBytes) { #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) if (nBytes >= 1 && (addr + nBytes) <= SRAM_SIZE) { @@ -266,7 +188,7 @@ void MCP79412RTC::sramRead(byte addr, byte *values, byte nBytes) // Address (addr) is constrained to the range (0, 127). // Can't leverage page write function because a write can't start // mid-page. -void MCP79412RTC::eepromWrite(byte addr, byte value) +void MCP79412RTC::eepromWrite(uint8_t addr, uint8_t value) { i2cBeginTransmission(EEPROM_ADDR); i2cWrite( addr & (EEPROM_SIZE - 1) ); @@ -280,12 +202,12 @@ void MCP79412RTC::eepromWrite(byte addr, byte value) // is ruthlessly coerced into a valid value. // Number of bytes (nBytes) must be between 1 and 8, other values // result in no action. -void MCP79412RTC::eepromWrite(byte addr, byte *values, byte nBytes) +void MCP79412RTC::eepromWrite(uint8_t addr, uint8_t* values, uint8_t nBytes) { if (nBytes >= 1 && nBytes <= EEPROM_PAGE_SIZE) { i2cBeginTransmission(EEPROM_ADDR); i2cWrite( addr & ~(EEPROM_PAGE_SIZE - 1) & (EEPROM_SIZE - 1) ); - for (byte i=0; i= 1 && (addr + nBytes) <= EEPROM_SIZE) { @@ -318,22 +240,22 @@ void MCP79412RTC::eepromRead(byte addr, byte *values, byte nBytes) i2cBeginTransmission(EEPROM_ADDR); i2cWrite( addr & (EEPROM_SIZE - 1) ); i2cEndTransmission(); - i2cRequestFrom( (uint8_t)EEPROM_ADDR, nBytes ); - for (byte i=0; i= -127 && value <= 127) { - calibVal = abs(value); + uint8_t calibVal = abs(value); if (value < 0) calibVal += 128; ramWrite(CALIB_REG, calibVal); } @@ -370,13 +290,13 @@ void MCP79412RTC::calibWrite(int value) // Read the unique ID. // For the MCP79411 (EUI-48), the first two bytes will contain 0xFF. // Caller must provide an 8-byte array to contain the results. -void MCP79412RTC::idRead(byte *uniqueID) +void MCP79412RTC::idRead(uint8_t* uniqueID) { i2cBeginTransmission(EEPROM_ADDR); i2cWrite(UNIQUE_ID_ADDR); i2cEndTransmission(); i2cRequestFrom( EEPROM_ADDR, UNIQUE_ID_SIZE ); - for (byte i=0; i 3) { ctrlReg &= ~_BV(SQWE); @@ -487,13 +405,11 @@ void MCP79412RTC::squareWave(uint8_t freq) // Set an alarm time. Sets the alarm registers only, does not enable // the alarm. See enableAlarm(). -void MCP79412RTC::setAlarm(uint8_t alarmNumber, time_t alarmTime) +void MCP79412RTC::setAlarm(ALARM_NBR_t alarmNumber, time_t alarmTime) { - tmElements_t tm; - uint8_t day; // need to preserve bits in the day (of week) register - - alarmNumber &= 0x01; // ensure a valid alarm number + uint8_t day; // need to preserve bits in the day (of week) register ramRead( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG) , &day, 1); + tmElements_t tm; breakTime(alarmTime, tm); i2cBeginTransmission(RTC_ADDR); i2cWrite( ALM0_REG + alarmNumber * (ALM1_REG - ALM0_REG) ); @@ -508,14 +424,12 @@ void MCP79412RTC::setAlarm(uint8_t alarmNumber, time_t alarmTime) // Enable or disable an alarm, and set the trigger criteria, // e.g. match only seconds, only minutes, entire time and date, etc. -void MCP79412RTC::enableAlarm(uint8_t alarmNumber, uint8_t alarmType) +void MCP79412RTC::enableAlarm(ALARM_NBR_t alarmNumber, uint8_t alarmType) { - uint8_t day; // alarm day register has config & flag bits uint8_t ctrl; // control register has alarm enable bits - - alarmNumber &= 0x01; // ensure a valid alarm number ramRead(CTRL_REG, &ctrl, 1); if (alarmType < ALM_DISABLE) { + uint8_t day; // alarm day register has config & flag bits ramRead(ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); day = ( day & 0x87 ) | alarmType << 4; // reset interrupt flag, OR in the config bits ramWrite(ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); @@ -530,11 +444,9 @@ void MCP79412RTC::enableAlarm(uint8_t alarmNumber, uint8_t alarmType) // Returns true or false depending on whether the given alarm has been // triggered, and resets the alarm "interrupt" flag. This is not a real // interrupt, just a bit that's set when an alarm is triggered. -bool MCP79412RTC::alarm(uint8_t alarmNumber) +bool MCP79412RTC::alarm(ALARM_NBR_t alarmNumber) { uint8_t day; // alarm day register has config & flag bits - - alarmNumber &= 0x01; // ensure a valid alarm number ramRead( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); if (day & _BV(ALMIF)) { day &= ~_BV(ALMIF); // turn off the alarm "interrupt" flag @@ -550,7 +462,6 @@ bool MCP79412RTC::alarm(uint8_t alarmNumber) void MCP79412RTC::out(bool level) { uint8_t ctrlReg; - ramRead(CTRL_REG, &ctrlReg, 1); if (level) ctrlReg |= _BV(OUT); @@ -572,7 +483,6 @@ void MCP79412RTC::out(bool level) void MCP79412RTC::alarmPolarity(bool polarity) { uint8_t alm0Day; - ramRead(ALM0_DAY, &alm0Day, 1); if (polarity) alm0Day |= _BV(OUT); @@ -586,11 +496,11 @@ void MCP79412RTC::alarmPolarity(bool polarity) bool MCP79412RTC::isRunning() { i2cBeginTransmission(RTC_ADDR); - i2cWrite((uint8_t)TIME_REG); + i2cWrite(TIME_REG); i2cEndTransmission(); // request just the seconds register - i2cRequestFrom(RTC_ADDR, 1); + i2cRequestFrom(RTC_ADDR, static_cast(1)); return i2cRead() & _BV(ST); } @@ -600,7 +510,6 @@ bool MCP79412RTC::isRunning() void MCP79412RTC::vbaten(bool enable) { uint8_t day; - ramRead(DAY_REG, &day, 1); if (enable) day |= _BV(VBATEN); @@ -623,6 +532,116 @@ uint8_t __attribute__ ((noinline)) MCP79412RTC::bcd2dec(uint8_t n) return n - 6 * (n >> 4); } -#if defined ARDUINO_ARCH_AVR -MCP79412RTC RTC; // instantiate an RTC object for AVR only -#endif +// dump rtc registers, 16 bytes at a time. +// always dumps a multiple of 16 bytes. +// duplicate rows are suppressed and indicated with an asterisk. +void MCP79412RTC::dumpRegs(uint32_t startAddr, uint32_t nBytes) +{ + Serial.print(F("\nRTC REGISTERS\n")); + uint32_t nRows = (nBytes + 15) >> 4; + + uint8_t d[16], last[16]; + uint32_t aLast {startAddr}; + for (uint32_t r = 0; r < nRows; r++) { + uint32_t a = startAddr + 16 * r; + ramRead(a, d, 16); + bool same {true}; + for (int i=0; i<16; ++i) { + if (last[i] != d[i]) same = false; + } + if (!same || r == 0 || r == nRows-1) { + Serial.print(F("0x")); + if ( a < 16 * 16 * 16 ) Serial.print('0'); + if ( a < 16 * 16 ) Serial.print('0'); + if ( a < 16 ) Serial.print('0'); + Serial.print(a, HEX); + Serial.print(a == aLast+16 || r == 0 ? " " : "* "); + for ( int16_t c = 0; c < 16; c++ ) { + if ( d[c] < 16 ) Serial.print('0'); + Serial.print(d[c], HEX); + Serial.print(c == 7 ? " " : " " ); + } + Serial.println(); + aLast = a; + } + for (int i=0; i<16; ++i) { + last[i] = d[i]; + } + } +} + +// dump rtc sram, 16 bytes at a time. +// always dumps a multiple of 16 bytes. +// duplicate rows are suppressed and indicated with an asterisk. +void MCP79412RTC::dumpSRAM(uint32_t startAddr, uint32_t nBytes) +{ + Serial.print(F("\nRTC SRAM\n")); + uint32_t nRows = (nBytes + 15) >> 4; + + uint8_t d[16], last[16]; + uint32_t aLast {startAddr}; + for (uint32_t r = 0; r < nRows; r++) { + uint32_t a = startAddr + 16 * r; + sramRead(a, d, 16); + bool same {true}; + for (int i=0; i<16; ++i) { + if (last[i] != d[i]) same = false; + } + if (!same || r == 0 || r == nRows-1) { + Serial.print(F("0x")); + if ( a < 16 * 16 * 16 ) Serial.print('0'); + if ( a < 16 * 16 ) Serial.print('0'); + if ( a < 16 ) Serial.print('0'); + Serial.print(a, HEX); + Serial.print(a == aLast+16 || r == 0 ? " " : "* "); + for ( int16_t c = 0; c < 16; c++ ) { + if ( d[c] < 16 ) Serial.print('0'); + Serial.print(d[c], HEX); + Serial.print(c == 7 ? " " : " " ); + } + Serial.println(); + aLast = a; + } + for (int i=0; i<16; ++i) { + last[i] = d[i]; + } + } +} + +// dump rtc eeprom, 16 bytes at a time. +// always dumps a multiple of 16 bytes. +// duplicate rows are suppressed and indicated with an asterisk. +void MCP79412RTC::dumpEEPROM(uint32_t startAddr, uint32_t nBytes) +{ + Serial.print(F("\nRTC EEPROM\n")); + uint32_t nRows = (nBytes + 15) >> 4; + + uint8_t d[16], last[16]; + uint32_t aLast {startAddr}; + for (uint32_t r = 0; r < nRows; r++) { + uint32_t a = startAddr + 16 * r; + eepromRead(a, d, 16); + bool same {true}; + for (int i=0; i<16; ++i) { + if (last[i] != d[i]) same = false; + } + if (!same || r == 0 || r == nRows-1) { + Serial.print(F("0x")); + if ( a < 16 * 16 * 16 ) Serial.print('0'); + if ( a < 16 * 16 ) Serial.print('0'); + if ( a < 16 ) Serial.print('0'); + Serial.print(a, HEX); + Serial.print(a == aLast+16 || r == 0 ? " " : "* "); + for ( int16_t c = 0; c < 16; c++ ) { + if ( d[c] < 16 ) Serial.print('0'); + Serial.print(d[c], HEX); + Serial.print(c == 7 ? " " : " " ); + } + Serial.println(); + aLast = a; + } + for (int i=0; i<16; ++i) { + last[i] = d[i]; + } + } +} diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index a32e620..da03dc3 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -23,83 +23,160 @@ #include #include // https://github.com/PaulStoffregen/Time -// Alarm types for use with the enableAlarm() function -enum { - ALM_MATCH_SECONDS, - ALM_MATCH_MINUTES, - ALM_MATCH_HOURS, - ALM_MATCH_DAY, // triggers alarm at midnight - ALM_MATCH_DATE, - ALM_RESERVED_5, // do not use - ALM_RESERVED_6, // do not use - ALM_MATCH_DATETIME, - ALM_DISABLE -}; +// define consistent I2C functions +#if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) +#include +#define i2cBegin TinyWireM.begin +#define i2cBeginTransmission TinyWireM.beginTransmission +#define i2cEndTransmission TinyWireM.endTransmission +#define i2cRequestFrom TinyWireM.requestFrom +#define i2cRead TinyWireM.receive +#define i2cWrite TinyWireM.send +#else +#include +#define i2cBegin Wire.begin +#define i2cBeginTransmission Wire.beginTransmission +#define i2cEndTransmission Wire.endTransmission +#define i2cRequestFrom Wire.requestFrom +#define i2cRead Wire.read +#define i2cWrite Wire.write +#endif -// Square-wave output frequencies for use with squareWave() function -enum { - SQWAVE_1_HZ, - SQWAVE_4096_HZ, - SQWAVE_8192_HZ, - SQWAVE_32768_HZ, - SQWAVE_NONE -}; +#ifndef _BV +#define _BV(bit) (1 << (bit)) +#endif -// constants for use with alarm functions -#define ALARM_0 0 -#define ALARM_1 1 +#ifndef BUFFER_LENGTH // a horrible and limiting kludge for samd (arduino zero) +#define BUFFER_LENGTH 32 +#endif class MCP79412RTC { public: - MCP79412RTC(bool initI2C = true); + // Alarm types for use with the enableAlarm() function + enum ALARM_TYPES_t { + ALM_MATCH_SECONDS, + ALM_MATCH_MINUTES, + ALM_MATCH_HOURS, + ALM_MATCH_DAY, // triggers alarm at midnight + ALM_MATCH_DATE, + ALM_RESERVED_5, // do not use + ALM_RESERVED_6, // do not use + ALM_MATCH_DATETIME, + ALM_DISABLE + }; + + // Square-wave output frequencies for use with squareWave() function + enum SQWAVE_FREQS_t { + SQWAVE_1_HZ, + SQWAVE_4096_HZ, + SQWAVE_8192_HZ, + SQWAVE_32768_HZ, + SQWAVE_NONE + }; + + // constants for use with alarm functions + enum ALARM_NBR_t { + ALARM_0, + ALARM_1 + }; + + // MCP7941x I2C Addresses + static constexpr uint8_t + RTC_ADDR {0x6F}, + EEPROM_ADDR {0x57}; + + // MCP7941x Register Addresses + static constexpr uint8_t + TIME_REG {0x00}, // 7 registers, Seconds, Minutes, Hours, DOW, Date, Month, Year + DAY_REG {0x03}, // the RTC Day register contains the OSCON, VBAT, and VBATEN bits + YEAR_REG {0x06}, // RTC year register + CTRL_REG {0x07}, // control register + CALIB_REG {0x08}, // calibration register + UNLOCK_ID_REG {0x09}, // unlock ID register + ALM0_REG {0x0A}, // alarm 0, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month + ALM1_REG {0x11}, // alarm 1, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month + ALM0_DAY {0x0D}, // DOW register has alarm config/flag bits + PWRDWN_TS_REG {0x18}, // power-down timestamp, 4 registers, Minutes, Hours, Date, Month + PWRUP_TS_REG {0x1C}, // power-up timestamp, 4 registers, Minutes, Hours, Date, Month + TIMESTAMP_SIZE {8}, // number of bytes in the two timestamp registers + SRAM_START_ADDR {0x20}, // first SRAM address + SRAM_SIZE {64}, // number of bytes of SRAM + EEPROM_SIZE {128}, // number of bytes of EEPROM + EEPROM_PAGE_SIZE{8}, // number of bytes on an EEPROM page + UNIQUE_ID_ADDR {0xF0}, // starting address for unique ID + UNIQUE_ID_SIZE {8}; // number of bytes in unique ID + + // Control Register bits + static constexpr uint8_t + OUT {7}, // sets logic level on MFP when not used as square wave output + SQWE {6}, // set to enable square wave output + ALM1 {5}, // alarm 1 is active + ALM0 {4}, // alarm 0 is active + EXTOSC {3}, // set to drive the RTC registers from an external oscillator instead of a crystal + RS2 {2}, // RS2:0 set square wave output frequency: 0==1Hz, 1==4096Hz, 2==8192Hz, 3=32768Hz + RS1 {1}, + RS0 {0}; + + // Other Control Bits + static constexpr uint8_t + ST {7}, // Seconds register (TIME_REG) oscillator start/stop bit, 1==Start, 0==Stop + HR1224 {6}, // Hours register (TIME_REG+2) 12 or 24 hour mode (24 hour mode==0) + AMPM {5}, // Hours register (TIME_REG+2) AM/PM bit for 12 hour mode + OSCON {5}, // Day register (TIME_REG+3) oscillator running (set and cleared by hardware) + VBAT {4}, // Day register (TIME_REG+3) set by hardware when Vcc fails and RTC runs on battery. + // VBAT is cleared by software, clearing VBAT also clears the timestamp registers + VBATEN {3}, // Day register (TIME_REG+3) VBATEN==1 enables backup battery, VBATEN==0 disconnects the VBAT pin (e.g. to save battery) + LP {5}; // Month register (TIME_REG+5) leap year bit + + // Alarm Control Bits + static constexpr uint8_t + ALMPOL {7}, // Alarm Polarity: Defines the logic level for the MFP when an alarm is triggered. + ALMC2 {6}, // Alarm configuration bits determine how alarms match. See ALM_MATCH defines below. + ALMC1 {5}, + ALMC0 {4}, + ALMIF {3}; // Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. + + MCP79412RTC() {}; + MCP79412RTC(bool initI2C) { (void)initI2C; } // undocumented for backward compatibility void begin(); static time_t get(); static void set(time_t t); static bool read(tmElements_t &tm); static void write(tmElements_t &tm); - void sramWrite(byte addr, byte value); - void sramWrite(byte addr, byte *values, byte nBytes); - byte sramRead(byte addr); - void sramRead(byte addr, byte *values, byte nBytes); - void eepromWrite(byte addr, byte value); - void eepromWrite(byte addr, byte *values, byte nBytes); - byte eepromRead(byte addr); - void eepromRead(byte addr, byte *values, byte nBytes); - int calibRead(); - void calibWrite(int value); - void idRead(byte *uniqueID); - void getEUI64(byte *uniqueID); - bool powerFail(time_t *powerDown, time_t *powerUp); + void sramWrite(uint8_t addr, uint8_t value); + void sramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes); + uint8_t sramRead(uint8_t addr); + void sramRead(uint8_t addr, uint8_t* values, uint8_t nBytes); + void eepromWrite(uint8_t addr, uint8_t value); + void eepromWrite(uint8_t addr, uint8_t* values, uint8_t nBytes); + uint8_t eepromRead(uint8_t addr); + void eepromRead(uint8_t addr, uint8_t* values, uint8_t nBytes); + int16_t calibRead(); + void calibWrite(int16_t value); + void idRead(uint8_t* uniqueID); + void getEUI64(uint8_t* uniqueID); + bool powerFail(time_t* powerDown, time_t* powerUp); void squareWave(uint8_t freq); - void setAlarm(uint8_t alarmNumber, time_t alarmTime); - void enableAlarm(uint8_t alarmNumber, uint8_t alarmType); - bool alarm(uint8_t alarmNumber); + void setAlarm(ALARM_NBR_t alarmNumber, time_t alarmTime); + void enableAlarm(ALARM_NBR_t alarmNumber, uint8_t alarmType); + bool alarm(ALARM_NBR_t alarmNumber); void out(bool level); void alarmPolarity(bool polarity); bool isRunning(); void vbaten(bool enable); + void dumpRegs(uint32_t startAddr=0, uint32_t nBytes=32); + void dumpSRAM(uint32_t startAddr=0, uint32_t nBytes=64); + void dumpEEPROM(uint32_t startAddr=0, uint32_t nBytes=128); private: - static void ramWrite(byte addr, byte value); - static void ramWrite(byte addr, byte *values, byte nBytes); - static byte ramRead(byte addr); - static void ramRead(byte addr, byte *values, byte nBytes); - static byte eepromWait(); + static void ramWrite(uint8_t addr, uint8_t value); + static void ramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes); + static uint8_t ramRead(uint8_t addr); + static void ramRead(uint8_t addr, uint8_t* values, uint8_t nBytes); + static uint8_t eepromWait(); static uint8_t dec2bcd(uint8_t num); static uint8_t bcd2dec(uint8_t num); }; -#if defined ARDUINO_ARCH_AVR -extern MCP79412RTC RTC; -#endif - -#ifndef _BV -#define _BV(bit) (1 << (bit)) -#endif - -#ifndef BUFFER_LENGTH // a horrible and limiting kludge for samd (arduino zero) -#define BUFFER_LENGTH 32 -#endif - #endif From 7c62cb499ce51be99ff0bbb048f61f417c14e02a Mon Sep 17 00:00:00 2001 From: JChristensen Date: Tue, 26 Apr 2022 21:15:24 -0400 Subject: [PATCH 12/22] Change register and bit names to agree with the datasheet. --- examples/SetSerial/SetSerial.ino | 1 - keywords.txt | 3 ++ src/MCP79412RTC.cpp | 92 ++++++++++++++++---------------- src/MCP79412RTC.h | 66 ++++++++++++----------- 4 files changed, 82 insertions(+), 80 deletions(-) diff --git a/examples/SetSerial/SetSerial.ino b/examples/SetSerial/SetSerial.ino index 7b0c617..78c454e 100644 --- a/examples/SetSerial/SetSerial.ino +++ b/examples/SetSerial/SetSerial.ino @@ -41,7 +41,6 @@ void setup() Serial.begin(115200); Serial << F( "\n" __FILE__ "\n" __DATE__ " " __TIME__ "\n" ); myRTC.begin(); - myRTC.dumpRegs(); // setSyncProvider() causes the Time library to synchronize with the // external RTC by calling myRTC.get() every five minutes by default. diff --git a/keywords.txt b/keywords.txt index b250cde..82dfb6b 100644 --- a/keywords.txt +++ b/keywords.txt @@ -21,3 +21,6 @@ out KEYWORD2 alarmPolarity KEYWORD2 isRunning KEYWORD2 vbaten KEYWORD2 +dumpRegs KEYWORD2 +dumpSRAM KEYWORD2 +dumpEEPROM KEYWORD2 diff --git a/src/MCP79412RTC.cpp b/src/MCP79412RTC.cpp index 701116d..a803f33 100644 --- a/src/MCP79412RTC.cpp +++ b/src/MCP79412RTC.cpp @@ -51,19 +51,19 @@ void MCP79412RTC::set(time_t t) bool MCP79412RTC::read(tmElements_t &tm) { i2cBeginTransmission(RTC_ADDR); - i2cWrite(TIME_REG); + i2cWrite(RTCSEC); if (i2cEndTransmission() != 0) { return false; } else { // request 7 bytes (secs, min, hr, dow, date, mth, yr) i2cRequestFrom(RTC_ADDR, static_cast(tmNbrFields)); - tm.Second = bcd2dec(i2cRead() & ~_BV(ST)); + tm.Second = bcd2dec(i2cRead() & ~_BV(STOSC)); tm.Minute = bcd2dec(i2cRead()); tm.Hour = bcd2dec(i2cRead() & ~_BV(HR1224)); // assumes 24hr clock - tm.Wday = i2cRead() & ~(_BV(OSCON) | _BV(VBAT) | _BV(VBATEN)); // mask off OSCON, VBAT, VBATEN bits + tm.Wday = i2cRead() & ~(_BV(OSCRUN) | _BV(PWRFAIL) | _BV(VBATEN)); // mask off OSCRUN, PWRFAIL, VBATEN bits tm.Day = bcd2dec(i2cRead()); - tm.Month = bcd2dec(i2cRead() & ~_BV(LP)); // mask off the leap year bit + tm.Month = bcd2dec(i2cRead() & ~_BV(LPYR)); // mask off the leap year bit tm.Year = y2kYearToTm(bcd2dec(i2cRead())); return true; } @@ -73,8 +73,8 @@ bool MCP79412RTC::read(tmElements_t &tm) void MCP79412RTC::write(tmElements_t &tm) { i2cBeginTransmission(RTC_ADDR); - i2cWrite(TIME_REG); - i2cWrite(0x00); // stops the oscillator (Bit 7, ST == 0) + i2cWrite(RTCSEC); + i2cWrite(0x00); // stops the oscillator (Bit 7, STOSC == 0) i2cWrite(dec2bcd(tm.Minute)); i2cWrite(dec2bcd(tm.Hour)); // sets 24 hour format (Bit 6 == 0) i2cWrite(tm.Wday | _BV(VBATEN)); // enable battery backup operation @@ -84,8 +84,8 @@ void MCP79412RTC::write(tmElements_t &tm) i2cEndTransmission(); i2cBeginTransmission(RTC_ADDR); - i2cWrite(TIME_REG); - i2cWrite(dec2bcd(tm.Second) | _BV(ST)); // set the seconds and start the oscillator (Bit 7, ST == 1) + i2cWrite(RTCSEC); + i2cWrite(dec2bcd(tm.Second) | _BV(STOSC)); // set the seconds and start the oscillator (Bit 7, STOSC == 1) i2cEndTransmission(); } @@ -251,13 +251,11 @@ uint8_t MCP79412RTC::eepromWait() uint8_t waitCount{0}; uint8_t txStatus; - do - { + do { ++waitCount; i2cBeginTransmission(EEPROM_ADDR); i2cWrite(0); txStatus = i2cEndTransmission(); - } while (txStatus != 0); return waitCount; @@ -269,7 +267,7 @@ uint8_t MCP79412RTC::eepromWait() // it and return it to the caller as a regular twos-complement integer. int16_t MCP79412RTC::calibRead() { - uint8_t val {ramRead(CALIB_REG)}; + uint8_t val {ramRead(OSCTRIM)}; if ( val & 0x80 ) return -(val & 0x7F); else return val; @@ -283,7 +281,7 @@ void MCP79412RTC::calibWrite(int16_t value) if (value >= -127 && value <= 127) { uint8_t calibVal = abs(value); if (value < 0) calibVal += 128; - ramWrite(CALIB_REG, calibVal); + ramWrite(OSCTRIM, calibVal); } } @@ -322,7 +320,7 @@ void MCP79412RTC::getEUI64(uint8_t* uniqueID) // Check to see if a power failure has occurred. If so, returns TRUE // as the function value, and returns the power down and power up // timestamps. After returning the time stamps, the RTC's timestamp -// registers are cleared and the VBAT bit which indicates a power +// registers are cleared and the PWRFAIL bit which indicates a power // failure is reset. // // Note that the power down and power up timestamp registers do not @@ -341,12 +339,12 @@ void MCP79412RTC::getEUI64(uint8_t* uniqueID) bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) { uint8_t day, yr; // copies of the RTC Day and Year registers - ramRead(DAY_REG, &day, 1); - ramRead(YEAR_REG, &yr, 1); + ramRead(RTCWKDAY, &day, 1); + ramRead(RTCYEAR, &yr, 1); yr = y2kYearToTm(bcd2dec(yr)); - if ( day & _BV(VBAT) ) { + if ( day & _BV(PWRFAIL) ) { i2cBeginTransmission(RTC_ADDR); - i2cWrite(PWRDWN_TS_REG); + i2cWrite(PWRDNMIN); i2cEndTransmission(); i2cRequestFrom(RTC_ADDR, TIMESTAMP_SIZE); // read both timestamp registers, 8 bytes total @@ -367,7 +365,7 @@ bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) *powerDown = makeTime(dn); *powerUp = makeTime(up); - // clear the VBAT bit, which causes the RTC hardware to clear the timestamps too. + // clear the PWRFAIL bit, which causes the RTC hardware to clear the timestamps too. // I suppose there is a risk here that the day has changed since we read it, // but the Day of Week is actually redundant data and the makeTime() function // does not use it. This could be an issue if someone is reading the RTC @@ -375,8 +373,8 @@ bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) // and also because we don't provide a method to read the RTC clock/calendar // registers directly, we won't lose any sleep about it at this point unless // some issue is actually brought to our attention ;-) - day &= ~_BV(VBAT); - ramWrite(DAY_REG, &day , 1); + day &= ~_BV(PWRFAIL); + ramWrite(RTCWKDAY, &day , 1); // adjust the powerDown timestamp if needed (see notes above) if (*powerDown > *powerUp) { @@ -393,14 +391,14 @@ bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) void MCP79412RTC::squareWave(uint8_t freq) { uint8_t ctrlReg; - ramRead(CTRL_REG, &ctrlReg, 1); + ramRead(CONTROL, &ctrlReg, 1); if (freq > 3) { - ctrlReg &= ~_BV(SQWE); + ctrlReg &= ~_BV(SQWEN); } else { - ctrlReg = (ctrlReg & 0xF8) | _BV(SQWE) | freq; + ctrlReg = (ctrlReg & 0xF8) | _BV(SQWEN) | freq; } - ramWrite(CTRL_REG, &ctrlReg, 1); + ramWrite(CONTROL, &ctrlReg, 1); } // Set an alarm time. Sets the alarm registers only, does not enable @@ -408,14 +406,14 @@ void MCP79412RTC::squareWave(uint8_t freq) void MCP79412RTC::setAlarm(ALARM_NBR_t alarmNumber, time_t alarmTime) { uint8_t day; // need to preserve bits in the day (of week) register - ramRead( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG) , &day, 1); + ramRead( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC) , &day, 1); tmElements_t tm; breakTime(alarmTime, tm); i2cBeginTransmission(RTC_ADDR); - i2cWrite( ALM0_REG + alarmNumber * (ALM1_REG - ALM0_REG) ); + i2cWrite( ALM0SEC + alarmNumber * (ALM1SEC - ALM0SEC) ); i2cWrite(dec2bcd(tm.Second)); i2cWrite(dec2bcd(tm.Minute)); - i2cWrite(dec2bcd(tm.Hour)); // sets 24 hour format (Bit 6 == 0) + i2cWrite(dec2bcd(tm.Hour)); // sets 24 hour format (Bit 6 == 0) i2cWrite( (day & 0xF8) + tm.Wday ); i2cWrite(dec2bcd(tm.Day)); i2cWrite(dec2bcd(tm.Month)); @@ -427,18 +425,18 @@ void MCP79412RTC::setAlarm(ALARM_NBR_t alarmNumber, time_t alarmTime) void MCP79412RTC::enableAlarm(ALARM_NBR_t alarmNumber, uint8_t alarmType) { uint8_t ctrl; // control register has alarm enable bits - ramRead(CTRL_REG, &ctrl, 1); + ramRead(CONTROL, &ctrl, 1); if (alarmType < ALM_DISABLE) { uint8_t day; // alarm day register has config & flag bits - ramRead(ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); + ramRead(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); day = ( day & 0x87 ) | alarmType << 4; // reset interrupt flag, OR in the config bits - ramWrite(ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); - ctrl |= _BV(ALM0 + alarmNumber); // enable the alarm + ramWrite(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + ctrl |= _BV(ALM0EN + alarmNumber); // enable the alarm } else { - ctrl &= ~(_BV(ALM0 + alarmNumber)); // disable the alarm + ctrl &= ~(_BV(ALM0EN + alarmNumber)); // disable the alarm } - ramWrite(CTRL_REG, &ctrl, 1); + ramWrite(CONTROL, &ctrl, 1); } // Returns true or false depending on whether the given alarm has been @@ -447,10 +445,10 @@ void MCP79412RTC::enableAlarm(ALARM_NBR_t alarmNumber, uint8_t alarmType) bool MCP79412RTC::alarm(ALARM_NBR_t alarmNumber) { uint8_t day; // alarm day register has config & flag bits - ramRead( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); - if (day & _BV(ALMIF)) { - day &= ~_BV(ALMIF); // turn off the alarm "interrupt" flag - ramWrite( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); + ramRead( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + if (day & _BV(ALMxIF)) { + day &= ~_BV(ALMxIF); // turn off the alarm "interrupt" flag + ramWrite( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); return true; } else @@ -462,12 +460,12 @@ bool MCP79412RTC::alarm(ALARM_NBR_t alarmNumber) void MCP79412RTC::out(bool level) { uint8_t ctrlReg; - ramRead(CTRL_REG, &ctrlReg, 1); + ramRead(CONTROL, &ctrlReg, 1); if (level) ctrlReg |= _BV(OUT); else ctrlReg &= ~_BV(OUT); - ramWrite(CTRL_REG, &ctrlReg, 1); + ramWrite(CONTROL, &ctrlReg, 1); } // Specifies the logic level on the Multi-Function Pin (MFP) when an @@ -483,25 +481,25 @@ void MCP79412RTC::out(bool level) void MCP79412RTC::alarmPolarity(bool polarity) { uint8_t alm0Day; - ramRead(ALM0_DAY, &alm0Day, 1); + ramRead(ALM0WKDAY, &alm0Day, 1); if (polarity) alm0Day |= _BV(OUT); else alm0Day &= ~_BV(OUT); - ramWrite(ALM0_DAY, &alm0Day, 1); + ramWrite(ALM0WKDAY, &alm0Day, 1); } -// Check to see if the RTC's oscillator is started (ST bit in seconds +// Check to see if the RTC's oscillator is started (STOSC bit in seconds // register). Returns true if started. bool MCP79412RTC::isRunning() { i2cBeginTransmission(RTC_ADDR); - i2cWrite(TIME_REG); + i2cWrite(RTCSEC); i2cEndTransmission(); // request just the seconds register i2cRequestFrom(RTC_ADDR, static_cast(1)); - return i2cRead() & _BV(ST); + return i2cRead() & _BV(STOSC); } // Set or clear the VBATEN bit. Setting the bit powers the clock and @@ -510,13 +508,13 @@ bool MCP79412RTC::isRunning() void MCP79412RTC::vbaten(bool enable) { uint8_t day; - ramRead(DAY_REG, &day, 1); + ramRead(RTCWKDAY, &day, 1); if (enable) day |= _BV(VBATEN); else day &= ~_BV(VBATEN); - ramWrite(DAY_REG, &day, 1); + ramWrite(RTCWKDAY, &day, 1); return; } diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index da03dc3..a10e559 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -88,54 +88,56 @@ class MCP79412RTC // MCP7941x Register Addresses static constexpr uint8_t - TIME_REG {0x00}, // 7 registers, Seconds, Minutes, Hours, DOW, Date, Month, Year - DAY_REG {0x03}, // the RTC Day register contains the OSCON, VBAT, and VBATEN bits - YEAR_REG {0x06}, // RTC year register - CTRL_REG {0x07}, // control register - CALIB_REG {0x08}, // calibration register - UNLOCK_ID_REG {0x09}, // unlock ID register - ALM0_REG {0x0A}, // alarm 0, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month - ALM1_REG {0x11}, // alarm 1, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month - ALM0_DAY {0x0D}, // DOW register has alarm config/flag bits - PWRDWN_TS_REG {0x18}, // power-down timestamp, 4 registers, Minutes, Hours, Date, Month - PWRUP_TS_REG {0x1C}, // power-up timestamp, 4 registers, Minutes, Hours, Date, Month + RTCSEC {0x00}, // 7 registers, Seconds, Minutes, Hours, DOW, Date, Month, Year + RTCWKDAY {0x03}, // the RTC Day register contains the OSCRUN, PWRFAIL, and VBATEN bits + RTCYEAR {0x06}, // RTC year register + CONTROL {0x07}, // control register + OSCTRIM {0x08}, // oscillator calibration register + EEUNLOCK {0x09}, // protected eeprom unlock register + ALM0SEC {0x0A}, // alarm 0, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month + ALM1SEC {0x11}, // alarm 1, 6 registers, Seconds, Minutes, Hours, DOW, Date, Month + ALM0WKDAY {0x0D}, // DOW register has alarm config/flag bits + PWRDNMIN {0x18}, // power-down timestamp, 4 registers, Minutes, Hours, Date, Month + PWRUPMIN {0x1C}, // power-up timestamp, 4 registers, Minutes, Hours, Date, Month TIMESTAMP_SIZE {8}, // number of bytes in the two timestamp registers SRAM_START_ADDR {0x20}, // first SRAM address SRAM_SIZE {64}, // number of bytes of SRAM EEPROM_SIZE {128}, // number of bytes of EEPROM EEPROM_PAGE_SIZE{8}, // number of bytes on an EEPROM page - UNIQUE_ID_ADDR {0xF0}, // starting address for unique ID + UNIQUE_ID_ADDR {0xF0}, // starting address for unique ID in EEPROM UNIQUE_ID_SIZE {8}; // number of bytes in unique ID // Control Register bits static constexpr uint8_t OUT {7}, // sets logic level on MFP when not used as square wave output - SQWE {6}, // set to enable square wave output - ALM1 {5}, // alarm 1 is active - ALM0 {4}, // alarm 0 is active - EXTOSC {3}, // set to drive the RTC registers from an external oscillator instead of a crystal - RS2 {2}, // RS2:0 set square wave output frequency: 0==1Hz, 1==4096Hz, 2==8192Hz, 3=32768Hz - RS1 {1}, - RS0 {0}; + SQWEN {6}, // set to enable square wave output + ALM1EN {5}, // alarm 1 is active + ALM0EN {4}, // alarm 0 is active + EXTOSC {3}, // enable external oscillator instead of a crystal + CRSTRIM {2}, // coarse trim mode enable + SQWFS1 {1}, // SQWFS1:0 square wave output freq: 0==1Hz, 1==4096Hz, 2==8192Hz, 3=32768Hz + SQWFS0 {0}; // Other Control Bits static constexpr uint8_t - ST {7}, // Seconds register (TIME_REG) oscillator start/stop bit, 1==Start, 0==Stop - HR1224 {6}, // Hours register (TIME_REG+2) 12 or 24 hour mode (24 hour mode==0) - AMPM {5}, // Hours register (TIME_REG+2) AM/PM bit for 12 hour mode - OSCON {5}, // Day register (TIME_REG+3) oscillator running (set and cleared by hardware) - VBAT {4}, // Day register (TIME_REG+3) set by hardware when Vcc fails and RTC runs on battery. - // VBAT is cleared by software, clearing VBAT also clears the timestamp registers - VBATEN {3}, // Day register (TIME_REG+3) VBATEN==1 enables backup battery, VBATEN==0 disconnects the VBAT pin (e.g. to save battery) - LP {5}; // Month register (TIME_REG+5) leap year bit + STOSC {7}, // Seconds register (RTCSEC) oscillator start/stop bit, 1==Start, 0==Stop + HR1224 {6}, // Hours register (RTCHOUR) 12 or 24 hour mode (24 hour mode==0) + AMPM {5}, // Hours register (RTCHOUR) AM/PM bit for 12 hour mode + OSCRUN {5}, // Day register (RTCWKDAY) oscillator running (set and cleared by hardware) + PWRFAIL {4}, // Day register (RTCWKDAY) set by hardware when Vcc fails and RTC runs on battery. + // PWRFAIL is cleared by software, clearing PWRFAIL also + // clears the timestamp registers + VBATEN {3}, // Day register (RTCWKDAY) VBATEN==1 enables backup + // battery, VBATEN==0 disconnects the VBAT pin (e.g. to save battery) + LPYR {5}; // Month register (RTCMTH) leap year bit // Alarm Control Bits static constexpr uint8_t - ALMPOL {7}, // Alarm Polarity: Defines the logic level for the MFP when an alarm is triggered. - ALMC2 {6}, // Alarm configuration bits determine how alarms match. See ALM_MATCH defines below. - ALMC1 {5}, - ALMC0 {4}, - ALMIF {3}; // Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. + ALMPOL {7}, // Alarm Polarity: Defines the logic level for the MFP when an alarm is triggered. + ALMxMSK2 {6}, // Alarm configuration bits determine how alarms match. See ALARM_TYPES_t enum. + ALMxMSK1 {5}, + ALMxMSK0 {4}, + ALMxIF {3}; // Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. MCP79412RTC() {}; MCP79412RTC(bool initI2C) { (void)initI2C; } // undocumented for backward compatibility From 565428c0a28024e5c422972dfc31d8cf7a894a99 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Tue, 26 Apr 2022 21:28:18 -0400 Subject: [PATCH 13/22] Update keywords.txt and library.properties --- keywords.txt | 59 ++++++++++++++++++++++++++++++++++++++++++++++ library.properties | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/keywords.txt b/keywords.txt index 82dfb6b..228fac4 100644 --- a/keywords.txt +++ b/keywords.txt @@ -1,4 +1,7 @@ +# datatypes MCP79412RTC KEYWORD1 + +# methods & functions begin KEYWORD2 get KEYWORD2 set KEYWORD2 @@ -24,3 +27,59 @@ vbaten KEYWORD2 dumpRegs KEYWORD2 dumpSRAM KEYWORD2 dumpEEPROM KEYWORD2 + +# constants +ALM_MATCH_SECONDS LITERAL1 +ALM_MATCH_MINUTES LITERAL1 +ALM_MATCH_HOURS LITERAL1 +ALM_MATCH_DAY LITERAL1 +ALM_MATCH_DATE LITERAL1 +ALM_MATCH_DATETIME LITERAL1 +ALM_DISABLE LITERAL1 +SQWAVE_1_HZ LITERAL1 +SQWAVE_4096_HZ LITERAL1 +SQWAVE_8192_HZ LITERAL1 +SQWAVE_32768_HZ LITERAL1 +SQWAVE_NONE LITERAL1 +ALARM_0 LITERAL1 +ALARM_1 LITERAL1 +RTC_ADDR LITERAL1 +EEPROM_ADDR LITERAL1 +RTCSEC LITERAL1 +RTCWKDAY LITERAL1 +RTCYEAR LITERAL1 +CONTROL LITERAL1 +OSCTRIM LITERAL1 +EEUNLOCK LITERAL1 +ALM0SEC LITERAL1 +ALM1SEC LITERAL1 +ALM0WKDAY LITERAL1 +PWRDNMIN LITERAL1 +PWRUPMIN LITERAL1 +TIMESTAMP_SIZE LITERAL1 +SRAM_START_ADDR LITERAL1 +SRAM_SIZE LITERAL1 +EEPROM_SIZE LITERAL1 +EEPROM_PAGE_SIZE LITERAL1 +UNIQUE_ID_ADDR LITERAL1 +UNIQUE_ID_SIZE LITERAL1 +OUT LITERAL1 +SQWEN LITERAL1 +ALM1EN LITERAL1 +ALM0EN LITERAL1 +EXTOSC LITERAL1 +CRSTRIM LITERAL1 +SQWFS1 LITERAL1 +SQWFS0 LITERAL1 +STOSC LITERAL1 +HR1224 LITERAL1 +AMPM LITERAL1 +OSCRUN LITERAL1 +PWRFAIL LITERAL1 +VBATEN LITERAL1 +LPYR LITERAL1 +ALMPOL LITERAL1 +ALMxMSK2 LITERAL1 +ALMxMSK1 LITERAL1 +ALMxMSK0 LITERAL1 +ALMxIF LITERAL1 diff --git a/library.properties b/library.properties index 274e7b4..40598ad 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=MCP79412RTC -version=1.0.2 +version=2.0.0 author=Jack Christensen maintainer=Jack Christensen sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. From 959624066681cfc149c8f4dd38cbeb5683955b5b Mon Sep 17 00:00:00 2001 From: JChristensen Date: Wed, 27 Apr 2022 23:06:06 -0400 Subject: [PATCH 14/22] Update example sketches for new library version. Add an example sketch showing alarm usage. Add const to function parameters as appropriate. --- .../PowerOutageLogger/PowerOutageLogger.ino | 146 +++++++++--------- examples/SetSerial/SetSerial.ino | 3 +- examples/TimeRTC/TimeRTC.ino | 57 ++++--- examples/alarm_ex1/alarm_ex1.ino | 74 +++++++++ examples/rtcSet1/rtcSet1.ino | 18 ++- examples/rtcSet2/rtcSet2.ino | 17 +- examples/rtcSet3/rtcSet3.ino | 18 ++- src/MCP79412RTC.cpp | 82 ++++++---- src/MCP79412RTC.h | 56 +++---- 9 files changed, 290 insertions(+), 181 deletions(-) create mode 100644 examples/alarm_ex1/alarm_ex1.ino diff --git a/examples/PowerOutageLogger/PowerOutageLogger.ino b/examples/PowerOutageLogger/PowerOutageLogger.ino index 52eb24d..1ea1cf9 100644 --- a/examples/PowerOutageLogger/PowerOutageLogger.ino +++ b/examples/PowerOutageLogger/PowerOutageLogger.ino @@ -7,138 +7,140 @@ // Assumes the RTC is running and set to UTC. // A maximum of 7 outages (power down/up times) can be logged in the // RTC's SRAM. +// The logging data structure is automatically initialized if not +// present. An initialization can be forced with a button switch +// connected from pin 9 to ground. Hold the button down +// while resetting the MCU to initialize the logging data. // // Jack Christensen 23Aug2012 #include // https://github.com/JChristensen/MCP79412RTC -#include // http://arduiniana.org/libraries/streaming/ -#include // https://github.com/PaulStoffregen/Time +#include // https://github.com/janelia-arduino/Streaming #include // https://github.com/JChristensen/Timezone -#define FIRST_OUTAGE_ADDR 0x08 // address of first outage timestamps in RTC SRAM -#define OUTAGE_LENGTH 8 // 8 data bytes for each outage (start and end timestamps, both are time_t values) -#define MAX_OUTAGES 7 // maximum number of outage timestamp pairs that can be stored in SRAM -#define MAX_OUTAGE_ADDR FIRST_OUTAGE_ADDR + OUTAGE_LENGTH * (MAX_OUTAGES - 1) // last outage address -#define APP_ID 1 // APP_ID and 4 bytes of the RTC ID are stored in sram to provide - // a way to recognize that the logging data structure has been initialized -#define RTC_ID_LO 0x00 // lower 4 bytes of RTC unique ID are stored at sram addr 0x00 -#define APP_ID_ADDR 0x04 // address of appID (1) -#define NBR_OUTAGES_ADDR 0x05 // address containing number of outages currently stored in SRAM -#define NEXT_OUTAGE_ADDR 0x06 // address containing pointer to next outage -#define RFU_ADDR 0x07 // reserved for future use - -// US Eastern Time Zone (New York, Detroit) -TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; // Daylight time = UTC - 4 hours -TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; // Standard time = UTC - 5 hours -Timezone myTZ(myDST, mySTD); -TimeChangeRule *tcr; // pointer to the time change rule, used to get TZ abbrev -time_t utc, local, lastUTC; +MCP79412RTC myRTC; void setup() { + constexpr uint8_t initButton {9}; + pinMode(initButton, INPUT_PULLUP); + myRTC.begin(); Serial.begin(115200); + Serial << F( "\n" __FILE__ " " __DATE__ " " __TIME__ "\n" ); - setSyncProvider(RTC.get); // the function to get the time from the RTC + setSyncProvider(myRTC.get); // the function to get the time from the RTC Serial << "RTC SYNC"; if (timeStatus()!= timeSet) Serial << " FAIL"; Serial << endl; - //logClear(); + if (!digitalRead(initButton)) logClear(); logOutage(); + //myRTC.dumpSRAM(); } +// US Eastern Time Zone (New York, Detroit) +TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; // Daylight time = UTC - 4 hours +TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; // Standard time = UTC - 5 hours +Timezone myTZ(myDST, mySTD); +TimeChangeRule *tcr; // pointer to the time change rule, used to get TZ abbrev + void loop() { // nothing here in loop() has anything to do with logging power outages, - // we just print the time every second so that something is happening. - utc = now(); - if (utc != lastUTC) - { + // we just print the time once a minute so that something is happening. + static time_t lastUTC; + time_t utc = now(); + if (minute(utc) != minute(lastUTC)) { lastUTC = utc; - local = myTZ.toLocal(utc, &tcr); + time_t local = myTZ.toLocal(utc, &tcr); Serial << endl; printTime(utc, "UTC"); printTime(local, tcr -> abbrev); } } +// constants for logging +constexpr uint8_t + firstOutageAddr {0x08}, // address of first outage timestamps in RTC SRAM + outageLength {8}, // 8 data bytes for each outage (start and end timestamps, both are time_t values) + maxOutages {7}, // maximum number of outage timestamp pairs that can be stored in SRAM + lastOutageAddr {firstOutageAddr + outageLength * (maxOutages - 1)}, // last outage address + appID {1}, // appID and 4 bytes of the RTC ID are stored in sram to provide + // a way to recognize that the logging data structure has been initialized + rtcID {0x00}, // lower 4 bytes of RTC unique ID are stored at sram addr 0x00 + appAddr {0x04}, // address of appID in sram + nbrOutagesAddr {0x05}, // address containing number of outages currently stored in SRAM + nextOutageAddr {0x06}, // address containing pointer to next outage + rfuAddr {0x07}; // reserved for future use + // initialize the log data structure in the RTC SRAM if needed. // log a new outage if one occurred. // print out the outages logged. -void logOutage() -{ +void logOutage() { union { uint8_t b[8]; struct { uint32_t hi; uint32_t lo; }; - } uniqueID; // 8-byte RTC "unique ID" with access to upper and lower halves - - uint32_t loID; // lower half of the unique ID read from sram - uint8_t appID; // app ID read from sram - uint8_t nOutage; // number of outages stored in sram - uint8_t nextOutage; // address of next outage timestamps in sram - uint8_t outageAddr; // outage address in sram - time_t powerDown, powerUp; // power outage timestamps - - RTC.idRead(uniqueID.b); // get the RTC's ID - loID = read32(RTC_ID_LO); // if already initialized, the lower half of the ID is stored at SRAM addr 0x00, - appID = RTC.sramRead(APP_ID_ADDR); // and the app ID (1) is at addr 0x04. + } uniqueID; // 8-byte RTC "unique ID" with access to upper and lower halves + + myRTC.idRead(uniqueID.b); // get the RTC's ID + uint32_t loID = read32(rtcID); // if already initialized, the lower half of the ID is stored in SRAM, + uint8_t app = myRTC.sramRead(appAddr); // and also the app ID Serial << "RTC ID"; - for (uint8_t i=0; i<8; i++) - { + for (uint8_t i=0; i<8; i++) { Serial << (uniqueID.b[i] < 16 ? " 0" : " ") << _HEX(uniqueID.b[i]); } + Serial << endl; - if ( loID != uniqueID.lo || appID != 1 ) // logging initialized? - { - write32(RTC_ID_LO, uniqueID.lo); // least significant half of the RTC unique ID - RTC.sramWrite(APP_ID_ADDR, APP_ID); // app ID - RTC.sramWrite(NBR_OUTAGES_ADDR, 0); // number of outages - RTC.sramWrite(NEXT_OUTAGE_ADDR, FIRST_OUTAGE_ADDR); // next location for outage times - RTC.sramWrite(RFU_ADDR, 0); // reserved for future use + if ( loID != uniqueID.lo || app != appID ) { // logging initialized? + write32(rtcID, uniqueID.lo); // least significant half of the RTC unique ID + myRTC.sramWrite(appAddr, appID); // app ID + myRTC.sramWrite(nbrOutagesAddr, 0); // number of outages + myRTC.sramWrite(nextOutageAddr, firstOutageAddr); // next location for outage times + myRTC.sramWrite(rfuAddr, 0); // reserved for future use Serial << "Logging initialized" << endl; // no, do it now } // if an outage has occurred, record it - if ( RTC.powerFail(&powerDown, &powerUp) ) - { - nOutage = RTC.sramRead(NBR_OUTAGES_ADDR); - nextOutage = RTC.sramRead(NEXT_OUTAGE_ADDR); + time_t powerDown, powerUp; // power outage timestamps + uint8_t nOutage; // number of outages stored in sram + uint8_t nextOutage; // address of next outage timestamps in sram + if ( myRTC.powerFail(&powerDown, &powerUp) ) { + nOutage = myRTC.sramRead(nbrOutagesAddr); + nextOutage = myRTC.sramRead(nextOutageAddr); write32(nextOutage, powerDown); write32(nextOutage + 4, powerUp); - nextOutage += OUTAGE_LENGTH; - if (nextOutage > MAX_OUTAGE_ADDR) nextOutage = FIRST_OUTAGE_ADDR; - RTC.sramWrite(NEXT_OUTAGE_ADDR, nextOutage); - if (nOutage < MAX_OUTAGES) RTC.sramWrite(NBR_OUTAGES_ADDR, ++nOutage); + nextOutage += outageLength; + if (nextOutage > lastOutageAddr) nextOutage = firstOutageAddr; + myRTC.sramWrite(nextOutageAddr, nextOutage); + if (nOutage < maxOutages) myRTC.sramWrite(nbrOutagesAddr, ++nOutage); } // print out all the outages logged - nOutage = RTC.sramRead(NBR_OUTAGES_ADDR); - nextOutage = RTC.sramRead(NEXT_OUTAGE_ADDR); - outageAddr = nextOutage - OUTAGE_LENGTH; - if (outageAddr < FIRST_OUTAGE_ADDR) outageAddr = MAX_OUTAGE_ADDR; - Serial << endl << endl << "Power outages logged: " << _DEC(nOutage) << endl; - for (uint8_t i=nOutage; i>0; i--) - { + nOutage = myRTC.sramRead(nbrOutagesAddr); + nextOutage = myRTC.sramRead(nextOutageAddr); + uint8_t outageAddr = nextOutage - outageLength; + if (outageAddr < firstOutageAddr) outageAddr = lastOutageAddr; + Serial << endl << "Power outages logged: " << _DEC(nOutage) << endl; + for (uint8_t i=nOutage; i>0; i--) { powerDown = read32(outageAddr); powerUp = read32(outageAddr + 4); Serial << endl << _DEC(i) << ": Power down "; printTime(myTZ.toLocal(powerDown, &tcr), tcr -> abbrev); Serial << _DEC(i) << ": Power up "; printTime(myTZ.toLocal(powerUp, &tcr), tcr -> abbrev); - outageAddr -= OUTAGE_LENGTH; - if (outageAddr < FIRST_OUTAGE_ADDR) outageAddr = MAX_OUTAGE_ADDR; + outageAddr -= outageLength; + if (outageAddr < firstOutageAddr) outageAddr = lastOutageAddr; } } // initialize the logging data structure and log data void logClear() { - for (uint8_t i=0; i // https://github.com/JChristensen/MCP79412RTC #include // http://arduiniana.org/libraries/streaming/ -#include // https://github.com/PaulStoffregen/Time MCP79412RTC myRTC; @@ -133,7 +132,7 @@ void loop() } // format and print a time_t value -void printTime(time_t t) +void printTime(const time_t t) { char buf[25]; char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer) diff --git a/examples/TimeRTC/TimeRTC.ino b/examples/TimeRTC/TimeRTC.ino index 3f730ae..9a36b78 100644 --- a/examples/TimeRTC/TimeRTC.ino +++ b/examples/TimeRTC/TimeRTC.ino @@ -1,50 +1,49 @@ // Arduino MCP79412RTC Library // https://github.com/JChristensen/MCP79412RTC // TimeRTC.ino -// Example code illustrating Time library with Real Time Clock. -// This example is identical to the example provided with the Time Library, -// only the #include statement has been changed to include the MCP79412RTC library. +// Example sketch showing basic usage. #include // http://github.com/JChristensen/MCP79412RTC -#include // https://www.pjrc.com/teensy/td_libs_DS1307RTC.html -#include // https://www.arduino.cc/en/Reference/Wire + +MCP79412RTC myRTC; void setup() { - Serial.begin(9600); - setSyncProvider(RTC.get); // the function to get the time from the RTC - if(timeStatus()!= timeSet) - Serial.println("Unable to sync with the RTC"); - else - Serial.println("RTC has set the system time"); + myRTC.begin(); + Serial.begin(115200); + setSyncProvider(myRTC.get); // the function to get the time from the RTC + if (timeStatus() != timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); } void loop() { - digitalClockDisplay(); - delay(1000); + digitalClockDisplay(); + delay(1000); } +// digital clock display of the time void digitalClockDisplay() { - // digital clock display of the time - Serial.print(hour()); - printDigits(minute()); - printDigits(second()); - Serial.print(" "); - Serial.print(day()); - Serial.print(" "); - Serial.print(month()); - Serial.print(" "); - Serial.print(year()); - Serial.println(); + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); } +// utility function for digital clock display: prints preceding colon and leading 0 void printDigits(int digits) { - // utility function for digital clock display: prints preceding colon and leading 0 - Serial.print(":"); - if(digits < 10) - Serial.print('0'); - Serial.print(digits); + Serial.print(":"); + if (digits < 10) + Serial.print('0'); + Serial.print(digits); } diff --git a/examples/alarm_ex1/alarm_ex1.ino b/examples/alarm_ex1/alarm_ex1.ino new file mode 100644 index 0000000..61058b5 --- /dev/null +++ b/examples/alarm_ex1/alarm_ex1.ino @@ -0,0 +1,74 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// MCP79412RTC Alarm Example Sketch #1 +// +// Set Alarm 0 to occur once a minute at 5 seconds after the minute. +// Detect the alarm by polling the MFP output as well as the RTC alarm flag. +// +// Hardware: +// Arduino Uno, MCP79410/11/12 RTC. +// Connect RTC SDA to Arduino pin A4. +// Connect RTC SCL to Arduino pin A5. +// +// Jack Christensen 27Apr2022 + +#include // https://github.com/JChristensen/MCP79412RTC +#include // https://github.com/janelia-arduino/Streaming + +MCP79412RTC myRTC; +constexpr uint8_t mfp {3}; // connect to RTC multi-function pin. + +void setup() +{ + Serial.begin(115200); + Serial << F( "\n" __FILE__ "\nCompiled " __DATE__ " " __TIME__ "\n" ); + pinMode(mfp, INPUT_PULLUP); + + // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags + myRTC.begin(); + myRTC.enableAlarm(MCP79412RTC::ALARM_0, MCP79412RTC::ALM_DISABLE); + myRTC.enableAlarm(MCP79412RTC::ALARM_1, MCP79412RTC::ALM_DISABLE); + myRTC.alarm(MCP79412RTC::ALARM_0); + myRTC.alarm(MCP79412RTC::ALARM_1); + myRTC.squareWave(MCP79412RTC::SQWAVE_NONE); + + // set Alarm 0 to occur at 5 seconds after every minute + myRTC.setAlarm(MCP79412RTC::ALARM_0, 2022, 1, 1, 0, 0, 5); + myRTC.enableAlarm(MCP79412RTC::ALARM_0, MCP79412RTC::ALM_MATCH_SECONDS); + + Serial << endl << millis() << " Start "; + printTime(myRTC.get()); + myRTC.dumpRegs(); +} + +void loop() +{ + if (!digitalRead(mfp)) { // is the mfp pulled low + Serial << millis() << " MFP LOW "; + printTime(myRTC.get()); + } + if ( myRTC.alarm(MCP79412RTC::ALARM_0) ) { // check alarm flag, clear it if set + Serial << millis() << " ALARM_0 "; + printTime(myRTC.get()); + } + if ( myRTC.alarm(MCP79412RTC::ALARM_1) ) { // check alarm flag, clear it if set + Serial << millis() << " ALARM_1 "; + printTime(myRTC.get()); + } + + delay(100); // no need to bombard the RTC continuously +} + +// format and print a time_t value +void printTime(const time_t t) +{ + char buf[25]; + char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer) + strcpy(m, monthShortStr(month(t))); + sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d", + hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t)); + Serial.println(buf); +} diff --git a/examples/rtcSet1/rtcSet1.ino b/examples/rtcSet1/rtcSet1.ino index 8fe845d..08611cc 100644 --- a/examples/rtcSet1/rtcSet1.ino +++ b/examples/rtcSet1/rtcSet1.ino @@ -10,17 +10,27 @@ // example may be of limited usefulness as an actual clock. #include // https://github.com/JChristensen/MCP79412RTC -#include // https://github.com/PaulStoffregen/Time + +MCP79412RTC myRTC; void setup() { + myRTC.begin(); delay(2000); - Serial.begin(9600); + Serial.begin(115200); - setTime(23, 31, 30, 13, 2, 2009); // set the system time to 23h31m30s on 13Feb2009 + setTime(23, 31, 30, 27, 4, 2022); // set the system time to 23h31m30s on 27Apr2022 // the setTime() function is from the Time.h library. // setTime(hour, minute, second, day, month, year); - RTC.set(now()); // set the RTC from the system time + + myRTC.set(now()); // set the RTC from the system time + + // sync the system time with the RTC every five minutes (by default) + setSyncProvider(myRTC.get); + if (timeStatus() != timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); } void loop() diff --git a/examples/rtcSet2/rtcSet2.ino b/examples/rtcSet2/rtcSet2.ino index d5a4d40..930b3cb 100644 --- a/examples/rtcSet2/rtcSet2.ino +++ b/examples/rtcSet2/rtcSet2.ino @@ -14,28 +14,29 @@ // example may be of limited usefulness as an actual clock. #include // https://github.com/JChristensen/MCP79412RTC -#include // https://github.com/PaulStoffregen/Time +MCP79412RTC myRTC; tmElements_t tm; void setup() { + myRTC.begin(); delay(2000); - Serial.begin(9600); + Serial.begin(115200); - tm.Hour = 23; // set the tm structure to 23h31m30s on Fri 13Feb2009 + tm.Hour = 23; // set the tm structure to 23h31m30s on 27Apr2022 tm.Minute = 31; tm.Second = 30; - tm.Year = 2009 - 1970; // tmElements_t.Year is the offset from 1970. - tm.Month = 2; - tm.Day = 13; + tm.Year = 2022 - 1970; // tmElements_t.Year is the offset from 1970. + tm.Month = 4; + tm.Day = 27; tm.Wday = dowFriday; // See enum in Time.h: Sun=1, Mon=2, ... Sat=7 - RTC.write(tm); // set the RTC from the tm structure + myRTC.write(tm); // set the RTC from the tm structure } void loop() { - RTC.read(tm); + myRTC.read(tm); Serial.print(tm.Hour, DEC); Serial.print(':'); Serial.print(tm.Minute,DEC); diff --git a/examples/rtcSet3/rtcSet3.ino b/examples/rtcSet3/rtcSet3.ino index 5e5b61f..11f3295 100644 --- a/examples/rtcSet3/rtcSet3.ino +++ b/examples/rtcSet3/rtcSet3.ino @@ -9,15 +9,18 @@ // Upload the sketch again to recompile it with the current time. #include // https://github.com/JChristensen/MCP79412RTC -#include // https://github.com/PaulStoffregen/Time + +MCP79412RTC myRTC; +time_t compileTime(const uint32_t fudge=10); // function prototype void setup() { + myRTC.begin(); delay(2000); - Serial.begin(9600); + Serial.begin(115200); setTime(compileTime()); // set the system time to the sketch compile time - RTC.set(now()); // set the RTC from the system time + myRTC.set(now()); // set the RTC from the system time } void loop() @@ -26,10 +29,11 @@ void loop() delay(1000); } -// Function to return the compile date and time as a time_t value -time_t compileTime() +// A function to return the compile date and time as a time_t value. +// The fudge argument (seconds) is used to adjust for compile and upload time, YMMV. +time_t compileTime(const uint32_t fudge) { - const uint32_t FUDGE(15); // fudge factor to allow for compile time (seconds, YMMV) + //const uint32_t fudge(10); // fudge factor to allow for compile time (seconds, YMMV) const char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec"; char chMon[3], *m; tmElements_t tm; @@ -46,7 +50,7 @@ time_t compileTime() tm.Minute = atoi(compTime + 3); tm.Second = atoi(compTime + 6); t = makeTime(tm); - return t + FUDGE; // add fudge factor to allow for compile time + return t + fudge; // add fudge factor to allow for compile time } // Print time (and date) given a time_t value diff --git a/src/MCP79412RTC.cpp b/src/MCP79412RTC.cpp index a803f33..ded7727 100644 --- a/src/MCP79412RTC.cpp +++ b/src/MCP79412RTC.cpp @@ -38,7 +38,7 @@ time_t MCP79412RTC::get() } // Set the RTC to the given time_t value. -void MCP79412RTC::set(time_t t) +void MCP79412RTC::set(const time_t t) { tmElements_t tm; @@ -48,7 +48,7 @@ void MCP79412RTC::set(time_t t) // Read the current time from the RTC and return it in a tmElements_t // structure. Returns false if RTC not present (I2C I/O error). -bool MCP79412RTC::read(tmElements_t &tm) +bool MCP79412RTC::read(tmElements_t& tm) { i2cBeginTransmission(RTC_ADDR); i2cWrite(RTCSEC); @@ -70,7 +70,7 @@ bool MCP79412RTC::read(tmElements_t &tm) } // Set the RTC's time from a tmElements_t structure. -void MCP79412RTC::write(tmElements_t &tm) +void MCP79412RTC::write(const tmElements_t& tm) { i2cBeginTransmission(RTC_ADDR); i2cWrite(RTCSEC); @@ -91,7 +91,7 @@ void MCP79412RTC::write(tmElements_t &tm) // Write a single byte to RTC RAM. // Valid address range is 0x00 - 0x5F, no checking. -void MCP79412RTC::ramWrite(uint8_t addr, uint8_t value) +void MCP79412RTC::ramWrite(const uint8_t addr, const uint8_t value) { ramWrite(addr, &value, 1); } @@ -100,7 +100,7 @@ void MCP79412RTC::ramWrite(uint8_t addr, uint8_t value) // Valid address range is 0x00 - 0x5F, no checking. // Number of bytes (nBytes) must be between 1 and 31 (Wire library // limitation). -void MCP79412RTC::ramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes) +void MCP79412RTC::ramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) { i2cBeginTransmission(RTC_ADDR); i2cWrite(addr); @@ -122,7 +122,7 @@ uint8_t MCP79412RTC::ramRead(uint8_t addr) // Valid address range is 0x00 - 0x5F, no checking. // Number of bytes (nBytes) must be between 1 and 32 (Wire library // limitation). -void MCP79412RTC::ramRead(uint8_t addr, uint8_t* values, uint8_t nBytes) +void MCP79412RTC::ramRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes) { i2cBeginTransmission(RTC_ADDR); i2cWrite(addr); @@ -133,7 +133,7 @@ void MCP79412RTC::ramRead(uint8_t addr, uint8_t* values, uint8_t nBytes) // Write a single byte to Static RAM. // Address (addr) is constrained to the range (0, 63). -void MCP79412RTC::sramWrite(uint8_t addr, uint8_t value) +void MCP79412RTC::sramWrite(const uint8_t addr, const uint8_t value) { ramWrite( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, &value, 1 ); } @@ -145,7 +145,7 @@ void MCP79412RTC::sramWrite(uint8_t addr, uint8_t value) // Invalid values for nBytes, or combinations of addr and nBytes // that would result in addressing past the last byte of SRAM will // result in no action. -void MCP79412RTC::sramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes) +void MCP79412RTC::sramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) { #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) if (nBytes >= 1 && (addr + nBytes) <= SRAM_SIZE) { @@ -158,7 +158,7 @@ void MCP79412RTC::sramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes) // Read a single byte from Static RAM. // Address (addr) is constrained to the range (0, 63). -uint8_t MCP79412RTC::sramRead(uint8_t addr) +uint8_t MCP79412RTC::sramRead(const uint8_t addr) { uint8_t value; @@ -173,7 +173,7 @@ uint8_t MCP79412RTC::sramRead(uint8_t addr) // Invalid values for nBytes, or combinations of addr and // nBytes that would result in addressing past the last byte of SRAM // result in no action. -void MCP79412RTC::sramRead(uint8_t addr, uint8_t* values, uint8_t nBytes) +void MCP79412RTC::sramRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes) { #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) if (nBytes >= 1 && (addr + nBytes) <= SRAM_SIZE) { @@ -188,7 +188,7 @@ void MCP79412RTC::sramRead(uint8_t addr, uint8_t* values, uint8_t nBytes) // Address (addr) is constrained to the range (0, 127). // Can't leverage page write function because a write can't start // mid-page. -void MCP79412RTC::eepromWrite(uint8_t addr, uint8_t value) +void MCP79412RTC::eepromWrite(const uint8_t addr, const uint8_t value) { i2cBeginTransmission(EEPROM_ADDR); i2cWrite( addr & (EEPROM_SIZE - 1) ); @@ -202,7 +202,7 @@ void MCP79412RTC::eepromWrite(uint8_t addr, uint8_t value) // is ruthlessly coerced into a valid value. // Number of bytes (nBytes) must be between 1 and 8, other values // result in no action. -void MCP79412RTC::eepromWrite(uint8_t addr, uint8_t* values, uint8_t nBytes) +void MCP79412RTC::eepromWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) { if (nBytes >= 1 && nBytes <= EEPROM_PAGE_SIZE) { i2cBeginTransmission(EEPROM_ADDR); @@ -215,7 +215,7 @@ void MCP79412RTC::eepromWrite(uint8_t addr, uint8_t* values, uint8_t nBytes) // Read a single byte from EEPROM. // Address (addr) is constrained to the range (0, 127). -uint8_t MCP79412RTC::eepromRead(uint8_t addr) +uint8_t MCP79412RTC::eepromRead(const uint8_t addr) { uint8_t value; @@ -230,7 +230,7 @@ uint8_t MCP79412RTC::eepromRead(uint8_t addr) // Invalid values for addr or nBytes, or combinations of addr and // nBytes that would result in addressing past the last byte of EEPROM // result in no action. -void MCP79412RTC::eepromRead(uint8_t addr, uint8_t* values, uint8_t nBytes) +void MCP79412RTC::eepromRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes) { #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) if (nBytes >= 1 && (addr + nBytes) <= EEPROM_SIZE) { @@ -276,7 +276,7 @@ int16_t MCP79412RTC::calibRead() // Write the calibration register. // Calibration value must be between -127 and 127, others result // in no action. See note above on the format of the calibration value. -void MCP79412RTC::calibWrite(int16_t value) +void MCP79412RTC::calibWrite(const int16_t value) { if (value >= -127 && value <= 127) { uint8_t calibVal = abs(value); @@ -388,7 +388,7 @@ bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) } // Enable or disable the square wave output. -void MCP79412RTC::squareWave(uint8_t freq) +void MCP79412RTC::squareWave(const SQWAVE_FREQS_t freq) { uint8_t ctrlReg; ramRead(CONTROL, &ctrlReg, 1); @@ -401,12 +401,12 @@ void MCP79412RTC::squareWave(uint8_t freq) ramWrite(CONTROL, &ctrlReg, 1); } -// Set an alarm time. Sets the alarm registers only, does not enable -// the alarm. See enableAlarm(). -void MCP79412RTC::setAlarm(ALARM_NBR_t alarmNumber, time_t alarmTime) +// Set an alarm to the given time_t value. Sets the alarm registers only, +// does not enable the alarm. See enableAlarm(). +void MCP79412RTC::setAlarm(const ALARM_NBR_t alarmNumber, const time_t alarmTime) { uint8_t day; // need to preserve bits in the day (of week) register - ramRead( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC) , &day, 1); + ramRead( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); tmElements_t tm; breakTime(alarmTime, tm); i2cBeginTransmission(RTC_ADDR); @@ -420,9 +420,27 @@ void MCP79412RTC::setAlarm(ALARM_NBR_t alarmNumber, time_t alarmTime) i2cEndTransmission(); } +// Set an alarm by specifying year, month, day, hour, minute, second. +// While the RTC does not use year for alarms, it's important to use the +// correct year to ensure the day of the week is calculated correctly. This +// is important especially if a day of week alarm will be used. +// Use a four-digit year, including century e.g. CCYY. +void MCP79412RTC::setAlarm(const ALARM_NBR_t alarmNumber, const uint16_t y, const uint8_t mon, + const uint8_t d, const uint8_t h, const uint8_t m, const uint8_t s) +{ + tmElements_t tm; + tm.Year = CalendarYrToTm(y); + tm.Month = mon; + tm.Day = d; + tm.Hour = h; + tm.Minute = m; + tm.Second = s; + setAlarm(alarmNumber, makeTime(tm)); +} + // Enable or disable an alarm, and set the trigger criteria, // e.g. match only seconds, only minutes, entire time and date, etc. -void MCP79412RTC::enableAlarm(ALARM_NBR_t alarmNumber, uint8_t alarmType) +void MCP79412RTC::enableAlarm(const ALARM_NBR_t alarmNumber, const ALARM_TYPES_t alarmType) { uint8_t ctrl; // control register has alarm enable bits ramRead(CONTROL, &ctrl, 1); @@ -442,7 +460,7 @@ void MCP79412RTC::enableAlarm(ALARM_NBR_t alarmNumber, uint8_t alarmType) // Returns true or false depending on whether the given alarm has been // triggered, and resets the alarm "interrupt" flag. This is not a real // interrupt, just a bit that's set when an alarm is triggered. -bool MCP79412RTC::alarm(ALARM_NBR_t alarmNumber) +bool MCP79412RTC::alarm(const ALARM_NBR_t alarmNumber) { uint8_t day; // alarm day register has config & flag bits ramRead( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); @@ -457,7 +475,7 @@ bool MCP79412RTC::alarm(ALARM_NBR_t alarmNumber) // Sets the logic level on the MFP when it's not being used as a // square wave or alarm output. The default is HIGH. -void MCP79412RTC::out(bool level) +void MCP79412RTC::out(const bool level) { uint8_t ctrlReg; ramRead(CONTROL, &ctrlReg, 1); @@ -478,14 +496,14 @@ void MCP79412RTC::out(bool level) // Note that the state of the MFP is independent of the alarm // "interrupt" flags, and the alarm() function will indicate when an // alarm is triggered regardless of the polarity. -void MCP79412RTC::alarmPolarity(bool polarity) +void MCP79412RTC::alarmPolarity(const bool polarity) { uint8_t alm0Day; ramRead(ALM0WKDAY, &alm0Day, 1); if (polarity) - alm0Day |= _BV(OUT); + alm0Day |= _BV(ALMPOL); else - alm0Day &= ~_BV(OUT); + alm0Day &= ~_BV(ALMPOL); ramWrite(ALM0WKDAY, &alm0Day, 1); } @@ -505,7 +523,7 @@ bool MCP79412RTC::isRunning() // 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. -void MCP79412RTC::vbaten(bool enable) +void MCP79412RTC::vbaten(const bool enable) { uint8_t day; ramRead(RTCWKDAY, &day, 1); @@ -519,13 +537,13 @@ void MCP79412RTC::vbaten(bool enable) } // Decimal-to-BCD conversion -uint8_t MCP79412RTC::dec2bcd(uint8_t n) +uint8_t MCP79412RTC::dec2bcd(const uint8_t n) { return n + 6 * (n / 10); } // BCD-to-Decimal conversion -uint8_t __attribute__ ((noinline)) MCP79412RTC::bcd2dec(uint8_t n) +uint8_t __attribute__ ((noinline)) MCP79412RTC::bcd2dec(const uint8_t n) { return n - 6 * (n >> 4); } @@ -533,7 +551,7 @@ uint8_t __attribute__ ((noinline)) MCP79412RTC::bcd2dec(uint8_t n) // dump rtc registers, 16 bytes at a time. // always dumps a multiple of 16 bytes. // duplicate rows are suppressed and indicated with an asterisk. -void MCP79412RTC::dumpRegs(uint32_t startAddr, uint32_t nBytes) +void MCP79412RTC::dumpRegs(const uint32_t startAddr, const uint32_t nBytes) { Serial.print(F("\nRTC REGISTERS\n")); uint32_t nRows = (nBytes + 15) >> 4; @@ -571,7 +589,7 @@ void MCP79412RTC::dumpRegs(uint32_t startAddr, uint32_t nBytes) // dump rtc sram, 16 bytes at a time. // always dumps a multiple of 16 bytes. // duplicate rows are suppressed and indicated with an asterisk. -void MCP79412RTC::dumpSRAM(uint32_t startAddr, uint32_t nBytes) +void MCP79412RTC::dumpSRAM(const uint32_t startAddr, const uint32_t nBytes) { Serial.print(F("\nRTC SRAM\n")); uint32_t nRows = (nBytes + 15) >> 4; @@ -609,7 +627,7 @@ void MCP79412RTC::dumpSRAM(uint32_t startAddr, uint32_t nBytes) // dump rtc eeprom, 16 bytes at a time. // always dumps a multiple of 16 bytes. // duplicate rows are suppressed and indicated with an asterisk. -void MCP79412RTC::dumpEEPROM(uint32_t startAddr, uint32_t nBytes) +void MCP79412RTC::dumpEEPROM(const uint32_t startAddr, const uint32_t nBytes) { Serial.print(F("\nRTC EEPROM\n")); uint32_t nRows = (nBytes + 15) >> 4; diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index a10e559..5c15d41 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -143,42 +143,44 @@ class MCP79412RTC MCP79412RTC(bool initI2C) { (void)initI2C; } // undocumented for backward compatibility void begin(); static time_t get(); - static void set(time_t t); - static bool read(tmElements_t &tm); - static void write(tmElements_t &tm); - void sramWrite(uint8_t addr, uint8_t value); - void sramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes); - uint8_t sramRead(uint8_t addr); - void sramRead(uint8_t addr, uint8_t* values, uint8_t nBytes); - void eepromWrite(uint8_t addr, uint8_t value); - void eepromWrite(uint8_t addr, uint8_t* values, uint8_t nBytes); - uint8_t eepromRead(uint8_t addr); - void eepromRead(uint8_t addr, uint8_t* values, uint8_t nBytes); + static void set(const time_t t); + static bool read(tmElements_t& tm); + static void write(const tmElements_t& tm); + void sramWrite(const uint8_t addr, const uint8_t value); + void sramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); + uint8_t sramRead(const uint8_t addr); + void sramRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes); + void eepromWrite(const uint8_t addr, const uint8_t value); + void eepromWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); + uint8_t eepromRead(const uint8_t addr); + void eepromRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes); int16_t calibRead(); - void calibWrite(int16_t value); + void calibWrite(const int16_t value); void idRead(uint8_t* uniqueID); void getEUI64(uint8_t* uniqueID); bool powerFail(time_t* powerDown, time_t* powerUp); - void squareWave(uint8_t freq); - void setAlarm(ALARM_NBR_t alarmNumber, time_t alarmTime); - void enableAlarm(ALARM_NBR_t alarmNumber, uint8_t alarmType); - bool alarm(ALARM_NBR_t alarmNumber); - void out(bool level); - void alarmPolarity(bool polarity); + void squareWave(const SQWAVE_FREQS_t freq); + void setAlarm(const ALARM_NBR_t alarmNumber, const time_t alarmTime); + void setAlarm(const ALARM_NBR_t alarmNumber, const uint16_t y, const uint8_t mon, + const uint8_t d, const uint8_t h, const uint8_t m, const uint8_t s); + void enableAlarm(const ALARM_NBR_t alarmNumber, const ALARM_TYPES_t alarmType); + bool alarm(const ALARM_NBR_t alarmNumber); + void out(const bool level); + void alarmPolarity(const bool polarity); bool isRunning(); - void vbaten(bool enable); - void dumpRegs(uint32_t startAddr=0, uint32_t nBytes=32); - void dumpSRAM(uint32_t startAddr=0, uint32_t nBytes=64); - void dumpEEPROM(uint32_t startAddr=0, uint32_t nBytes=128); + void vbaten(const bool enable); + void dumpRegs(const uint32_t startAddr=0, const uint32_t nBytes=32); + void dumpSRAM(const uint32_t startAddr=0, const uint32_t nBytes=64); + void dumpEEPROM(const uint32_t startAddr=0, const uint32_t nBytes=128); private: - static void ramWrite(uint8_t addr, uint8_t value); - static void ramWrite(uint8_t addr, uint8_t* values, uint8_t nBytes); + static void ramWrite(const uint8_t addr, const uint8_t value); + static void ramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); static uint8_t ramRead(uint8_t addr); - static void ramRead(uint8_t addr, uint8_t* values, uint8_t nBytes); + static void ramRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes); static uint8_t eepromWait(); - static uint8_t dec2bcd(uint8_t num); - static uint8_t bcd2dec(uint8_t num); + static uint8_t dec2bcd(const uint8_t num); + static uint8_t bcd2dec(const uint8_t num); }; #endif From 7cfacf02154fbe9b288dd3e191f69035bc4843da Mon Sep 17 00:00:00 2001 From: JChristensen Date: Fri, 16 Jun 2023 21:23:17 -0400 Subject: [PATCH 15/22] Update an example sketch. --- examples/rtcSetSerial/rtcSetSerial.ino | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/rtcSetSerial/rtcSetSerial.ino b/examples/rtcSetSerial/rtcSetSerial.ino index 0512286..1b68e6f 100644 --- a/examples/rtcSetSerial/rtcSetSerial.ino +++ b/examples/rtcSetSerial/rtcSetSerial.ino @@ -10,6 +10,7 @@ #include // https://github.com/JChristensen/MCP79412RTC #include // https://github.com/PaulStoffregen/Time +MCP79412RTC RTC; const uint32_t PRINT_INTERVAL(10000); // ms between printing the time uint32_t ms, msLast; From f993c7e24091050ff66ee471e91ea0e1381aeb54 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Wed, 22 Nov 2023 19:15:24 -0500 Subject: [PATCH 16/22] SetSerial example sketch: Improved error checking on user input when setting time or calibration. --- examples/SetSerial/SetSerial.ino | 94 ++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 36 deletions(-) diff --git a/examples/SetSerial/SetSerial.ino b/examples/SetSerial/SetSerial.ino index 5c84f7b..7d32e99 100644 --- a/examples/SetSerial/SetSerial.ino +++ b/examples/SetSerial/SetSerial.ino @@ -70,23 +70,41 @@ void setup() void loop() { - tmElements_t tm; - int cmdChar, y, oldCal, newCal; + // check for input, to set rtc time or calibration + if (Serial.available()) setRTC(); - // check for input, first character is a command, "S" to set date/time, or "C" to set the calibration register - if (Serial.available()) { - cmdChar = Serial.read(); + // print time and date every second + static time_t tLast; + time_t t { now() }; + if (t != tLast) { + tLast = t; + printTime(t); + } +} + +void setRTC() +{ + // first character is a command, "S" to set date/time, or "C" to set the calibration register + int cmdChar = Serial.read(); - switch (cmdChar) { - case 'S': - case 's': + switch (cmdChar) { + case 'S': + case 's': + delay(25); // wait for all the input to arrive + // check for input to set the RTC, minimum length is 13, i.e. yy,m,d,h,m,s + if (Serial.available() < 13) { + while (Serial.available()) Serial.read(); // dump extraneous input + Serial << F("Input error or timeout, try again.\n"); + } + else { // note that the tmElements_t Year member is an offset from 1970, // but the RTC wants the last two digits of the calendar year. // use the convenience macros from TimeLib.h to do the conversions. - y = Serial.parseInt(); + int y = Serial.parseInt(); if (y >= 100 && y < 1000) - Serial << F("Error: Year must be two digits or four digits!") << endl; + Serial << F("Error: Year must be two digits or four digits!\n"); else { + tmElements_t tm; if (y >= 1000) tm.Year = CalendarYrToTm(y); else //(y < 100) @@ -96,39 +114,43 @@ void loop() tm.Hour = Serial.parseInt(); tm.Minute = Serial.parseInt(); tm.Second = Serial.parseInt(); - time_t t = makeTime(tm); - myRTC.set(t); // use the time_t value to ensure correct weekday is set - setTime(t); - Serial << F("RTC set to: "); - printTime(t); - Serial << endl; + if (tm.Month == 0 || tm.Day == 0) { + while (Serial.available()) Serial.read(); // dump extraneous input + Serial << F("Input error or timeout, try again.\n"); + } + else { + time_t t = makeTime(tm); + myRTC.set(t); // use the time_t value to ensure correct weekday is set + setTime(t); + Serial << F("RTC set to: "); + printTime(t); + } } - break; + } + break; - case 'C': - case 'c': - newCal = Serial.parseInt(); - oldCal = myRTC.calibRead(); + case 'C': + case 'c': + delay(25); // wait for all the input to arrive + if (Serial.available() < 2) { // minimum valid input at this point is 2 chars + while (Serial.available()) Serial.read(); // dump extraneous input + Serial << F("Input error or timeout, try again.\n"); + } + else { + int newCal = Serial.parseInt(); + int oldCal = myRTC.calibRead(); myRTC.calibWrite(newCal); Serial << F("Calibration changed from ") << oldCal << F(" to ") << myRTC.calibRead() << endl; - break; - - default: - Serial << endl << F("Unrecognized command: ") << (char)cmdChar << endl; - break; - } + } + break; - // dump any extraneous input - while (Serial.available() > 0) Serial.read(); + default: + Serial << endl << F("Unrecognized command: ") << (char)cmdChar << endl; + break; } - // print time and date every second - static time_t tLast; - time_t t { now() }; - if (t != tLast) { - tLast = t; - printTime(t); - } + // dump any extraneous input + while (Serial.available()) Serial.read(); } // format and print a time_t value From 3a1d86f11a31295714dc30e38b7838f45ec0e780 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Thu, 22 May 2025 16:50:41 -0400 Subject: [PATCH 17/22] Finish doc for 2.0.0. --- README.md | 262 +++++++++++------- examples/rtcSetSerial/rtcSetSerial.ino | 115 -------- .../tiny79412_KnockBang.ino | 12 +- library.properties | 2 +- 4 files changed, 176 insertions(+), 215 deletions(-) delete mode 100644 examples/rtcSetSerial/rtcSetSerial.ino diff --git a/README.md b/README.md index 16bbcc5..895f6ca 100644 --- a/README.md +++ b/README.md @@ -2,19 +2,32 @@ https://github.com/JChristensen/MCP79412RTC README file Jack Christensen -Sep 2012 +May 2025 -## Introduction -**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](https://github.com/PaulStoffregen/Time). +## License +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. -The **MCP79412RTC** library is a drop-in replacement for the (older) **DS1307RTC** library by Michael Margolis that is supplied with the [Arduino Time library](https://www.arduino.cc/playground/Code/Time) (but not for [PJRC's newer version of the DS1307RTC library](https://www.pjrc.com/teensy/td_libs_DS1307RTC.html)). To change from using a DS1307 RTC to an MCP7941x RTC, it is only necessary to use `#include ` instead of `#include `. +You should have received a copy of the GNU General Public License along with this program. If not, see -The **MCP79412RTC** library also implements functions to support the additional features of the MCP7941x RTC. +## Important note: Library v2.0.0 +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 `MCP79412RTC` object, therefore each sketch needs to define one. (Previous versions of the library defined an `MCP79412RTC` object named `RTC`, although only for AVR architecture. Consider using a name other than `RTC` as 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 the `setup()` 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 `MCP79412RTC` class. Therefore, when using any of these names, it will be necessary to include the `MCP79412RTC` scope, e.g. `myRTC.alarm(MCP79412RTC::ALARM_1);` + - The example sketches and documentation have been updated to reflect these changes. + +## Introduction +**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](https://github.com/PaulStoffregen/Time). **For more information on the MCP79412, see:** +The [Microchip MCP79412 Product Page](https://www.microchip.com/en-us/product/MCP79412) for specs, datasheet, etc. [My Blog Post](http://goo.gl/MkBnjR), summarizing the features and advantages of the MCP79412 [My Power Outage Logger Project](http://goo.gl/RfM5os), an Arduino-based project featuring the MCP79412 -The [Microchip MCP79412 Product Page](http://goo.gl/SHfKe0) for specs, datasheet, etc. ## Examples The following example sketches are included with the **MCP79412RTC** library: @@ -23,16 +36,74 @@ The following example sketches are included with the **MCP79412RTC** library: - **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. - **SetSerial:** Set the RTC's date, time, and calibration register from the Arduino serial monitor. -- **rtcSetSerial:** Set the RTC via input from the Arduino serial monitor. -- **TimeRTC:** Same as the example of the same name provided with the **Time** library, demonstrating the interchangeability of the **MCP79412RTC** library with the **DS1307RTC** library. +- **TimeRTC:** Similar to the example of the same name provided with the **Time** library. - **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. -## Usage notes -Similar to the **DS1307RTC** library, the **MCP79412RTC** library instantiates an RTC object; the user does not need to do this. +## Enumerations +### ALARM_TYPES_t +##### Description +Symbolic names used with the `enableAlarm()` function described below. +##### Values +- 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. + +### ALARM_NBR_t +##### Description +Symbolic names used with alarm functions. +##### Values +- ALARM_0 +- ALARM_1 -## Functions for setting and reading the time +### SQWAVE_FREQS_t +##### Description +Symbolic names used with the squareWave() function (described below). +##### Values +- SQWAVE_1_HZ, +- SQWAVE_4096_HZ, +- SQWAVE_8192_HZ, +- SQWAVE_32768_HZ, +- SQWAVE_NONE + +## Constructor +### MCP79412RTC() +##### Description +Instantiates an `MCP79412RTC` object. +##### Syntax +`MCP79412RTC myRTC;` +##### Parameters +None. +##### Returns +None. +##### Example +```c++ +MCP79412RTC myRTC; +``` + +## Initialization function +### begin() +##### Description +Initializes the I2C bus. Calls `Wire.begin()`. +##### Syntax +`begin();` +##### Parameters +None. +##### Returns +None. +##### Example +```c++ +MCP79412RTC myRTC; +void setup() { + myRTC.begin(); +} +``` +## Functions for setting and reading the time ### get() ##### Description 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.). @@ -124,6 +195,89 @@ else //do something else ``` +## Alarm functions +The 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. + +### setAlarm(byte alarmNumber, time_t alarmTime) +##### Description +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. +##### Syntax +`RTC.setAlarm(alarmNumber, alarmTime);` +##### Parameters +**alarmNumber:** ALARM_0 or ALARM_1 *(byte)* +**alarmTime:** Date and time to set the alarm to *(time_t)* +##### Returns +None. +##### Example +```c++ +//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)); +``` + +### enableAlarm(byte alarmNumber, byte alarmType) +##### Description +Enable or disable the given alarm. +##### Syntax +`RTC.enableAlarm(alarmNumber, alarmType);` +##### Parameters +**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.) +##### Returns +None. +##### Example +```c++ +//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); +``` + +### alarm(byte alarmNumber) +##### Description +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. +##### Syntax +`RTC.alarm(byte alarmNumber);` +##### Parameters +**alarmNumber:** ALARM_0 or ALARM_1 *(byte)* +##### Returns +True if the alarm was triggered, else false *(boolean)* +##### Example +```c++ +if ( RTC.alarm(ALARM_0) ) + //alarm-0 has triggered +else + //alarm-0 has not triggered +``` + +### alarmPolarity(boolean polarity) +##### Description +Specifies 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. +##### Syntax +`RTC.alarmPolarity(boolean polarity);` +##### Parameters +**polarity:** HIGH or LOW *(boolean)* +##### Returns +None. +##### Example +```c++ +RTC.alarmPolarity(HIGH); //drives MFP high when an alarm is triggered +``` + ## Functions for reading and writing static RAM (SRAM) The 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. @@ -192,7 +346,7 @@ No function value returned. Bytes read from SRAM are returned to the **values** byte buf[8]; RTC.sramRead(56, buf, 8); ``` - + ## Functions for Reading and writing EEPROM 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. @@ -264,91 +418,7 @@ byte buf[8]; RTC.eepromRead(120, buf, 8); ``` -## Alarm functions -The 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. - -### setAlarm(byte alarmNumber, time_t alarmTime) -##### Description -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. -##### Syntax -`RTC.setAlarm(alarmNumber, alarmTime);` -##### Parameters -**alarmNumber:** ALARM_0 or ALARM_1 *(byte)* -**alarmTime:** Date and time to set the alarm to *(time_t)* -##### Returns -None. -##### Example -```c++ -//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)); -``` - -### enableAlarm(byte alarmNumber, byte alarmType) -##### Description -Enable or disable the given alarm. -##### Syntax -`RTC.enableAlarm(alarmNumber, alarmType);` -##### Parameters -**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.) -##### Returns -None. -##### Example -```c++ -//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); -``` - -### alarm(byte alarmNumber) -##### Description -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. -##### Syntax -`RTC.alarm(byte alarmNumber);` -##### Parameters -**alarmNumber:** ALARM_0 or ALARM_1 *(byte)* -##### Returns -True if the alarm was triggered, else false *(boolean)* -##### Example -```c++ -if ( RTC.alarm(ALARM_0) ) - //alarm-0 has triggered -else - //alarm-0 has not triggered -``` - -### alarmPolarity(boolean polarity) -##### Description -Specifies 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. -##### Syntax -`RTC.alarmPolarity(boolean polarity);` -##### Parameters -**polarity:** HIGH or LOW *(boolean)* -##### Returns -None. -##### Example -```c++ -RTC.alarmPolarity(HIGH); //drives MFP high when an alarm is triggered -``` - ## Calibration, power failure, and other functions - ### calibWrite(int value) ##### Description 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. diff --git a/examples/rtcSetSerial/rtcSetSerial.ino b/examples/rtcSetSerial/rtcSetSerial.ino deleted file mode 100644 index 1b68e6f..0000000 --- a/examples/rtcSetSerial/rtcSetSerial.ino +++ /dev/null @@ -1,115 +0,0 @@ -// Arduino MCP79412RTC Library -// https://github.com/JChristensen/MCP79412RTC -// Copyright (C) 2018 by Jack Christensen and licensed under -// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html -// -// Example sketch to set the RTC by entering a "Set" command on the -// serial monitor. Use a 24-hour clock and enter the command -// (case sensitive) exactly as follows: Set yyyy-mm-dd hh:mm:ss - -#include // https://github.com/JChristensen/MCP79412RTC -#include // https://github.com/PaulStoffregen/Time - -MCP79412RTC RTC; -const uint32_t PRINT_INTERVAL(10000); // ms between printing the time -uint32_t ms, msLast; - -void setup() -{ - delay(2000); - Serial.begin(9600); - - setSyncProvider(RTC.get); // the function to get the time from the RTC - Serial.print("RTC SYNC"); - if (timeStatus() != timeSet) Serial.print(" FAIL"); - Serial.println(); -} - -void loop() -{ - ms = millis(); - readCommand(); - if (ms - msLast >= PRINT_INTERVAL) { - msLast = ms; - printTime(now()); - } -} - -// Read command from the Arduino serial monitor to set the RTC. -// Case-sensitive and must be entered exactly as (24-hour clock): -// Set yyyy-mm-dd hh:mm:ss -void readCommand() -{ - char cmd[24] = "Set yyyy-mm-dd hh:mm:ss"; - - // serial terminal will send 23 char command plus line terminator (0x0A) - if (Serial.available() >= 24) { // enough characters for the whole command? - unsigned int i = 0; // yes, read the available characters - while (Serial.available() > 0) { - if (i >= sizeof(cmd)) { // more than we can enjoy - flushInput(); // clear out the input buffer - cmd[sizeof(cmd) - 1] = 0; // string terminator - Serial.print("Too long: "); - Serial.println(cmd); - return; - } - delay(2); // let the next character trickle in - char c = Serial.read(); - if (c >= ' ') cmd[i++] = c; // printable characters and spaces only - } - cmd[i] = 0; // put in string terminator - - tmElements_t tmSet; - if (strncmp(cmd, "Set ", 4) == 0) { - tmSet.Year = 1000 * (cmd[4] - '0') + 100 * (cmd[5] - '0') + 10 * (cmd[6] - '0') + cmd[7] - '0' - 1970; - tmSet.Month = 10 * (cmd[9] - '0') + cmd[10] - '0'; - tmSet.Day = 10 * (cmd[12] - '0') + cmd[13] - '0'; - tmSet.Hour = 10 * (cmd[15] - '0') + cmd[16] - '0'; - tmSet.Minute = 10 * (cmd[18] - '0') + cmd[19] - '0'; - tmSet.Second = 10 * (cmd[21] - '0') + cmd[22] - '0'; - time_t tSet = makeTime(tmSet); // convert to time_t - setTime(tSet); // set the system time - RTC.set(now()); // set the rtc - Serial.println("RTC set!"); - printTime(RTC.get()); - flushInput(); // discard any extraneous trailing characters - } - else { - Serial.print("Unknown: "); - Serial.println(cmd); - } - } -} - -void flushInput() -{ - do { - delay(2); - Serial.read(); - } while (Serial.available() > 0); -} - -// Print time (and date) given a time_t value -void printTime(time_t t) -{ - printI00(hour(t), ':'); - printI00(minute(t), ':'); - printI00(second(t), ' '); - Serial.print(dayShortStr(weekday(t))); - Serial.print(' '); - printI00(day(t), ' '); - Serial.print(monthShortStr(month(t))); - Serial.print(' '); - Serial.println(year(t)); -} - -// Print an integer in "00" format (with leading zero), -// followed by a delimiter. -// Input value assumed to be between 0 and 99. -void printI00(int val, char delim) -{ - if (val < 10) Serial.print('0'); - Serial.print(val); - Serial.print(delim); - return; -} diff --git a/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino b/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino index 9317cc7..9ab4c70 100644 --- a/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino +++ b/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino @@ -4,17 +4,20 @@ // GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html // // Example sketch. Digital clock display using an MCP79412 Real-Time -// Clock/Calendar and an ATtiny45/85 with a 1MHz system clock. +// Clock/Calendar and an ATtiny45/85 with a 1MHz system clock. // // Tested with Arduino 1.8.5, and: // ATTinyCore, https://github.com/SpenceKonde/ATTinyCore // TinyISP, https://github.com/Coding-Badly/TinyISP // +// Disable Link Time Optimization (LTO) as it causes compile errors (there +// are still some warnings.) +// // Run TinyISP on an ATmega microcontroller that does not have an LED // connected to pin 13 (SCK). The LED causes problems because the SPI // pins are also the I2C pins on the ATtiny. Connect MISO, MOSI, SCK // on the ATmega to the corresponding pins on the ATtiny through 220Ω -// resistors for safety. Use 4.7K pullup resistors on the ATtiny +// resistors for safety. Use 4.7k pullup resistors on the ATtiny // I2C bus. // // Jack Christensen 21Aug2013 @@ -23,13 +26,16 @@ #include // https://github.com/PaulStoffregen/Time #include // https://github.com/Coding-Badly/TinyDebugKnockBang +MCP79412RTC myRTC; + void setup() { + myRTC.begin(); Debug.begin(250000); // setSyncProvider() causes the Time library to synchronize with the // external RTC by calling RTC.get() every five minutes by default. - setSyncProvider(RTC.get); + setSyncProvider(myRTC.get); Debug.print(F("RTC Sync")); if (timeStatus() != timeSet) Debug.print(F(" FAIL!")); Debug.println(); diff --git a/library.properties b/library.properties index 40598ad..c963d07 100644 --- a/library.properties +++ b/library.properties @@ -6,5 +6,5 @@ sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. paragraph=Requires PJRC's improved Arduino Time Library, https://github.com/PaulStoffregen/Time category=Timing url=https://github.com/JChristensen/MCP79412RTC -architectures=avr +architectures=* depends=Time From 4434928727ba5bde7b5d08353ba4c8db0aa36d48 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 14 Jun 2025 18:20:09 -0400 Subject: [PATCH 18/22] Changes to work with alternate I2C peripherals, e.g. Wire1, etc. --- src/MCP79412RTC.h | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index 5c15d41..0380806 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -34,12 +34,12 @@ #define i2cWrite TinyWireM.send #else #include -#define i2cBegin Wire.begin -#define i2cBeginTransmission Wire.beginTransmission -#define i2cEndTransmission Wire.endTransmission -#define i2cRequestFrom Wire.requestFrom -#define i2cRead Wire.read -#define i2cWrite Wire.write +#define i2cBegin wire.begin +#define i2cBeginTransmission wire.beginTransmission +#define i2cEndTransmission wire.endTransmission +#define i2cRequestFrom wire.requestFrom +#define i2cRead wire.read +#define i2cWrite wire.write #endif #ifndef _BV @@ -139,13 +139,12 @@ class MCP79412RTC ALMxMSK0 {4}, ALMxIF {3}; // Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. - MCP79412RTC() {}; - MCP79412RTC(bool initI2C) { (void)initI2C; } // undocumented for backward compatibility + MCP79412RTC(TwoWire& tw=Wire) : wire(tw) {}; void begin(); - static time_t get(); - static void set(const time_t t); - static bool read(tmElements_t& tm); - static void write(const tmElements_t& tm); + time_t get(); + void set(const time_t t); + bool read(tmElements_t& tm); + void write(const tmElements_t& tm); void sramWrite(const uint8_t addr, const uint8_t value); void sramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); uint8_t sramRead(const uint8_t addr); @@ -174,13 +173,14 @@ class MCP79412RTC void dumpEEPROM(const uint32_t startAddr=0, const uint32_t nBytes=128); private: - static void ramWrite(const uint8_t addr, const uint8_t value); - static void ramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); - static uint8_t ramRead(uint8_t addr); - static void ramRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes); - static uint8_t eepromWait(); - static uint8_t dec2bcd(const uint8_t num); - static uint8_t bcd2dec(const uint8_t num); + TwoWire& wire; // reference to Wire or Wire1 + void ramWrite(const uint8_t addr, const uint8_t value); + void ramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); + uint8_t ramRead(uint8_t addr); + void ramRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes); + uint8_t eepromWait(); + uint8_t dec2bcd(const uint8_t num); + uint8_t bcd2dec(const uint8_t num); }; #endif From 3ffaf56dfdcce583ac341ce2b4922e19350928f4 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Tue, 17 Jun 2025 14:42:52 -0400 Subject: [PATCH 19/22] Add functionality to address different I2C peripherals. --- README.md | 25 ++++++++++++--- .../PowerOutageLogger/PowerOutageLogger.ino | 2 +- examples/SetSerial/SetSerial.ino | 2 +- examples/TimeRTC/TimeRTC.ino | 2 +- examples/rtcSet1/rtcSet1.ino | 2 +- examples/rtc_wire1/rtc_wire1.ino | 32 +++++++++++++++++++ .../tiny79412_KnockBang.ino | 2 +- library.properties | 2 +- src/MCP79412RTC.h | 2 +- 9 files changed, 59 insertions(+), 12 deletions(-) create mode 100644 examples/rtc_wire1/rtc_wire1.ino diff --git a/README.md b/README.md index 895f6ca..8a435cd 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,18 @@ This program is distributed in the hope that it will be useful, but WITHOUT ANY You should have received a copy of the GNU General Public License along with this program. If not, see -## Important note: Library v2.0.0 +## Version 3.0.0 notes +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](https://github.com/PaulStoffregen/Time), e.g.: +```c++ + setSyncProvider(myRTC.get); +``` +Needs to change as follows: +```c++ + 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. + +## Version 2.0.0 notes 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 `MCP79412RTC` object, therefore each sketch needs to define one. (Previous versions of the library defined an `MCP79412RTC` object named `RTC`, although only for AVR architecture. Consider using a name other than `RTC` as this can cause a name collision on some architectures.) @@ -35,6 +46,7 @@ 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. - **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. @@ -71,18 +83,21 @@ Symbolic names used with the squareWave() function (described below). - SQWAVE_NONE ## Constructor -### MCP79412RTC() +### MCP79412RTC(TwoWire& wire) ##### Description Instantiates an `MCP79412RTC` object. ##### Syntax -`MCP79412RTC myRTC;` +`MCP79412RTC myRTC(wire);` ##### Parameters -None. +**wire:** An optional parameter to specify which I2C bus to use. If omitted, defaults to `Wire`. *(TwoWire&)* ##### Returns None. ##### Example ```c++ -MCP79412RTC myRTC; +MCP79412RTC myRTC; // to use Wire +// or +MCP79412RTC myRTC(Wire1); // to use Wire1 + ``` ## Initialization function diff --git a/examples/PowerOutageLogger/PowerOutageLogger.ino b/examples/PowerOutageLogger/PowerOutageLogger.ino index 1ea1cf9..a4a528e 100644 --- a/examples/PowerOutageLogger/PowerOutageLogger.ino +++ b/examples/PowerOutageLogger/PowerOutageLogger.ino @@ -28,7 +28,7 @@ void setup() Serial.begin(115200); Serial << F( "\n" __FILE__ " " __DATE__ " " __TIME__ "\n" ); - setSyncProvider(myRTC.get); // the function to get the time from the RTC + setSyncProvider([](){return myRTC.get();}); // the function to get the time from the RTC Serial << "RTC SYNC"; if (timeStatus()!= timeSet) Serial << " FAIL"; Serial << endl; diff --git a/examples/SetSerial/SetSerial.ino b/examples/SetSerial/SetSerial.ino index 7d32e99..40dab5a 100644 --- a/examples/SetSerial/SetSerial.ino +++ b/examples/SetSerial/SetSerial.ino @@ -43,7 +43,7 @@ void setup() // setSyncProvider() causes the Time library to synchronize with the // external RTC by calling myRTC.get() every five minutes by default. - setSyncProvider(myRTC.get); + setSyncProvider([](){return myRTC.get();}); Serial << endl << F("RTC Sync"); if (timeStatus() != timeSet) Serial << F(" FAIL!"); Serial << endl; diff --git a/examples/TimeRTC/TimeRTC.ino b/examples/TimeRTC/TimeRTC.ino index 9a36b78..eebb75c 100644 --- a/examples/TimeRTC/TimeRTC.ino +++ b/examples/TimeRTC/TimeRTC.ino @@ -11,7 +11,7 @@ void setup() { myRTC.begin(); Serial.begin(115200); - setSyncProvider(myRTC.get); // the function to get the time from the RTC + setSyncProvider([](){return myRTC.get();}); // the function to get the time from the RTC if (timeStatus() != timeSet) Serial.println("Unable to sync with the RTC"); else diff --git a/examples/rtcSet1/rtcSet1.ino b/examples/rtcSet1/rtcSet1.ino index 08611cc..4725957 100644 --- a/examples/rtcSet1/rtcSet1.ino +++ b/examples/rtcSet1/rtcSet1.ino @@ -26,7 +26,7 @@ void setup() myRTC.set(now()); // set the RTC from the system time // sync the system time with the RTC every five minutes (by default) - setSyncProvider(myRTC.get); + setSyncProvider([](){return myRTC.get();}); if (timeStatus() != timeSet) Serial.println("Unable to sync with the RTC"); else diff --git a/examples/rtc_wire1/rtc_wire1.ino b/examples/rtc_wire1/rtc_wire1.ino new file mode 100644 index 0000000..fc634e3 --- /dev/null +++ b/examples/rtc_wire1/rtc_wire1.ino @@ -0,0 +1,32 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// rtc_wire1.ino +// Example sketch with the RTC on the Wire1 bus. +// Tested with Raspberry Pi Pico using the Arduino-Pico core, +// https://github.com/earlephilhower/arduino-pico + +#include // http://github.com/JChristensen/MCP79412RTC + +constexpr int sdaPin {26}, sclPin {27}; // I2C pins for Wire1 (your pins may vary) +MCP79412RTC myRTC(Wire1); + +void setup() +{ + Serial.begin(115200); + while (!Serial && millis() < 2000) delay(50); + + Wire1.setSDA(sdaPin); Wire1.setSCL(sclPin); + myRTC.begin(); + setSyncProvider([](){return myRTC.get();}); // the function to get the time from the RTC + if (timeStatus() != timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); +} + +void loop() +{ + Serial.printf("%.4d-%.2d-%.2d %.2d:%.2d:%.2d\n", year(), month(), day(), + hour(), minute(), second()); + delay(1000); +} diff --git a/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino b/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino index 9ab4c70..5aa9300 100644 --- a/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino +++ b/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino @@ -35,7 +35,7 @@ void setup() // setSyncProvider() causes the Time library to synchronize with the // external RTC by calling RTC.get() every five minutes by default. - setSyncProvider(myRTC.get); + setSyncProvider([](){return myRTC.get();}); Debug.print(F("RTC Sync")); if (timeStatus() != timeSet) Debug.print(F(" FAIL!")); Debug.println(); diff --git a/library.properties b/library.properties index c963d07..e9a1a06 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=MCP79412RTC -version=2.0.0 +version=3.0.0 author=Jack Christensen maintainer=Jack Christensen sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index 0380806..7b4f70a 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -173,7 +173,7 @@ class MCP79412RTC void dumpEEPROM(const uint32_t startAddr=0, const uint32_t nBytes=128); private: - TwoWire& wire; // reference to Wire or Wire1 + TwoWire& wire; // reference to Wire, Wire1, etc. void ramWrite(const uint8_t addr, const uint8_t value); void ramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); uint8_t ramRead(uint8_t addr); From 522054386f87e7037a7abbd186bd024ec94a2574 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Tue, 24 Jun 2025 10:46:55 -0400 Subject: [PATCH 20/22] Add abstract base class to support DS323x and MCP7941x RTCs. Modify method names and definitions to be consistent with DS3232RTC library. Add an example sketch. --- README.md | 1 + examples/rtc_interrupt/rtc_interrupt.ino | 97 ++++++++++++++++++++++++ src/GenericRTC.h | 31 ++++++++ src/MCP79412RTC.cpp | 77 ++++++++++--------- src/MCP79412RTC.h | 20 ++--- 5 files changed, 180 insertions(+), 46 deletions(-) create mode 100644 examples/rtc_interrupt/rtc_interrupt.ino create mode 100644 src/GenericRTC.h diff --git a/README.md b/README.md index 8a435cd..dd91b8c 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ The following example sketches are included with the **MCP79412RTC** library: - **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. diff --git a/examples/rtc_interrupt/rtc_interrupt.ino b/examples/rtc_interrupt/rtc_interrupt.ino new file mode 100644 index 0000000..3f00286 --- /dev/null +++ b/examples/rtc_interrupt/rtc_interrupt.ino @@ -0,0 +1,97 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2018 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Example sketch that uses a 1Hz interrupt from the RTC to keep time. +// This is an alternative to using the "setSyncProvider" function from +// the Time library to periodically sync the MCU's time with the RTC. +// +// Periodic synchronization will cause discontinuities in the MCU's perceived +// time of day. Depending on the relative frequency of the MCU's clock compared to +// that of the RTC, when synchronization occurs, a second according to the MCU's +// time may appear to be longer or shorter than one RTC second. Alternately, the +// MCU's time could jump backwards, or forward by more than a second. +// +// While this method requires setting up an interrupt and a few short +// functions to handle the interrupt and to set and read the time, +// it has the following advantages: (1) The MCU time is always exactly +// in step with the RTC time and is not dependent on the MCU's clock +// which will always drift relative to the RTC, and (2) It is more efficient +// as the RTC's time is only read once over the I2C bus and the interrupt +// service routine to increment the time is trivial. +// +// When using setSyncProvider and periodically synchronizing the MCU's time +// with the RTC, we effectively have two clocks instead of one. +// +// Jack Christensen 27Dec2018 + +#include // http://github.com/JChristensen/MCP79412RTC + +constexpr uint8_t RTC_1HZ_PIN {3}; // RTC provides a 1Hz interrupt signal on this pin + // Can use Pin 2 (INT0) or Pin 3 (INT1) with Arduino Uno +MCP79412RTC myRTC; + +void setup() +{ + Serial.begin(115200); + Serial.println(F("\n" __FILE__ " " __DATE__ " " __TIME__)); + + pinMode(RTC_1HZ_PIN, INPUT_PULLUP); // enable pullup on interrupt pin (RTC SQW pin is open drain) + attachInterrupt(digitalPinToInterrupt(RTC_1HZ_PIN), incrementTime, FALLING); + myRTC.begin(); + myRTC.squareWave(MCP79412RTC::SQWAVE_1_HZ); // 1 Hz square wave + + time_t utc = getUTC(); // synchronize with RTC + while ( utc == getUTC() ); // wait for increment to the next second + utc = myRTC.get(); // get the time from the RTC + setUTC(utc); // set our time to the RTC's time + Serial.println("Time set from RTC"); +} + +void loop() +{ + static time_t tLast; + time_t t = getUTC(); + + if (t != tLast) { + tLast = t; + printTime(t); + } +} + +volatile time_t isrUTC; // ISR's copy of current time in UTC + +// return current time +time_t getUTC() +{ + noInterrupts(); + time_t utc = isrUTC; + interrupts(); + return utc; +} + +// set the current time +void setUTC(time_t utc) +{ + noInterrupts(); + isrUTC = utc; + interrupts(); +} + +// 1Hz RTC interrupt handler increments the current time +void incrementTime() +{ + ++isrUTC; +} + +// format and print a time_t value +void printTime(time_t t) +{ + char buf[25]; + char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer) + strcpy(m, monthShortStr(month(t))); + sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d", + hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t)); + Serial.println(buf); +} diff --git a/src/GenericRTC.h b/src/GenericRTC.h new file mode 100644 index 0000000..933651d --- /dev/null +++ b/src/GenericRTC.h @@ -0,0 +1,31 @@ +// Abtract base class for: +// Arduino DS3232RTC Library https://github.com/JChristensen/DS3232RTC +// and Arduino MCP79412RTC Library // https://github.com/JChristensen/MCP79412RTC +// Copyright (C) 2025 by Jack Christensen and licensed under +// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html +// +// Allows a sketch to work with either type of RTC, determined at run time. + +#ifndef GENERIC_RTC_H_INCLUDED +#define GENERIC_RTC_H_INCLUDED + +#include +#include // https://github.com/PaulStoffregen/Time +#include + +class GenericRTC +{ + public: + GenericRTC(TwoWire& tw=Wire) : wire(tw) {}; + virtual void begin() = 0; + virtual time_t get() = 0; + virtual uint8_t set(const time_t t) = 0; + virtual uint8_t writeRTC(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) =0; + virtual uint8_t writeRTC(const uint8_t addr, const uint8_t value) = 0; + virtual uint8_t readRTC(const uint8_t addr, uint8_t* values, const uint8_t nBytes) = 0; + virtual uint8_t readRTC(const uint8_t addr) = 0; + + protected: + TwoWire& wire; // reference to Wire, Wire1, etc. +}; +#endif diff --git a/src/MCP79412RTC.cpp b/src/MCP79412RTC.cpp index ded7727..7392e6b 100644 --- a/src/MCP79412RTC.cpp +++ b/src/MCP79412RTC.cpp @@ -38,12 +38,13 @@ time_t MCP79412RTC::get() } // Set the RTC to the given time_t value. -void MCP79412RTC::set(const time_t t) +// Returns the I2C status (zero if successful). +uint8_t MCP79412RTC::set(const time_t t) { tmElements_t tm; breakTime(t, tm); - write(tm); + return ( write(tm) ); } // Read the current time from the RTC and return it in a tmElements_t @@ -70,7 +71,7 @@ bool MCP79412RTC::read(tmElements_t& tm) } // Set the RTC's time from a tmElements_t structure. -void MCP79412RTC::write(const tmElements_t& tm) +uint8_t MCP79412RTC::write(const tmElements_t& tm) { i2cBeginTransmission(RTC_ADDR); i2cWrite(RTCSEC); @@ -86,35 +87,36 @@ void MCP79412RTC::write(const tmElements_t& tm) i2cBeginTransmission(RTC_ADDR); i2cWrite(RTCSEC); i2cWrite(dec2bcd(tm.Second) | _BV(STOSC)); // set the seconds and start the oscillator (Bit 7, STOSC == 1) - i2cEndTransmission(); + uint8_t ret = i2cEndTransmission(); + return ret; } // Write a single byte to RTC RAM. // Valid address range is 0x00 - 0x5F, no checking. -void MCP79412RTC::ramWrite(const uint8_t addr, const uint8_t value) +uint8_t MCP79412RTC::writeRTC(const uint8_t addr, const uint8_t value) { - ramWrite(addr, &value, 1); + return ( writeRTC(addr, &value, 1) ); } // Write multiple bytes to RTC RAM. // Valid address range is 0x00 - 0x5F, no checking. // Number of bytes (nBytes) must be between 1 and 31 (Wire library // limitation). -void MCP79412RTC::ramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) +uint8_t MCP79412RTC::writeRTC(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) { i2cBeginTransmission(RTC_ADDR); i2cWrite(addr); for (uint8_t i=0; i= 1 && nBytes <= (BUFFER_LENGTH - 1) && (addr + nBytes) <= SRAM_SIZE) { #endif - ramWrite( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes ); + writeRTC( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes ); } } @@ -162,7 +165,7 @@ uint8_t MCP79412RTC::sramRead(const uint8_t addr) { uint8_t value; - ramRead( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, &value, 1 ); + readRTC( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, &value, 1 ); return value; } @@ -180,7 +183,7 @@ void MCP79412RTC::sramRead(const uint8_t addr, uint8_t* values, const uint8_t nB #else if (nBytes >= 1 && nBytes <= BUFFER_LENGTH && (addr + nBytes) <= SRAM_SIZE) { #endif - ramRead((addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes); + readRTC((addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes); } } @@ -267,7 +270,7 @@ uint8_t MCP79412RTC::eepromWait() // it and return it to the caller as a regular twos-complement integer. int16_t MCP79412RTC::calibRead() { - uint8_t val {ramRead(OSCTRIM)}; + uint8_t val {readRTC(OSCTRIM)}; if ( val & 0x80 ) return -(val & 0x7F); else return val; @@ -281,7 +284,7 @@ void MCP79412RTC::calibWrite(const int16_t value) if (value >= -127 && value <= 127) { uint8_t calibVal = abs(value); if (value < 0) calibVal += 128; - ramWrite(OSCTRIM, calibVal); + writeRTC(OSCTRIM, calibVal); } } @@ -339,8 +342,8 @@ void MCP79412RTC::getEUI64(uint8_t* uniqueID) bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) { uint8_t day, yr; // copies of the RTC Day and Year registers - ramRead(RTCWKDAY, &day, 1); - ramRead(RTCYEAR, &yr, 1); + readRTC(RTCWKDAY, &day, 1); + readRTC(RTCYEAR, &yr, 1); yr = y2kYearToTm(bcd2dec(yr)); if ( day & _BV(PWRFAIL) ) { i2cBeginTransmission(RTC_ADDR); @@ -374,7 +377,7 @@ bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) // registers directly, we won't lose any sleep about it at this point unless // some issue is actually brought to our attention ;-) day &= ~_BV(PWRFAIL); - ramWrite(RTCWKDAY, &day , 1); + writeRTC(RTCWKDAY, &day , 1); // adjust the powerDown timestamp if needed (see notes above) if (*powerDown > *powerUp) { @@ -391,14 +394,14 @@ bool MCP79412RTC::powerFail(time_t* powerDown, time_t* powerUp) void MCP79412RTC::squareWave(const SQWAVE_FREQS_t freq) { uint8_t ctrlReg; - ramRead(CONTROL, &ctrlReg, 1); + readRTC(CONTROL, &ctrlReg, 1); if (freq > 3) { ctrlReg &= ~_BV(SQWEN); } else { ctrlReg = (ctrlReg & 0xF8) | _BV(SQWEN) | freq; } - ramWrite(CONTROL, &ctrlReg, 1); + writeRTC(CONTROL, &ctrlReg, 1); } // Set an alarm to the given time_t value. Sets the alarm registers only, @@ -406,7 +409,7 @@ void MCP79412RTC::squareWave(const SQWAVE_FREQS_t freq) void MCP79412RTC::setAlarm(const ALARM_NBR_t alarmNumber, const time_t alarmTime) { uint8_t day; // need to preserve bits in the day (of week) register - ramRead( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + readRTC( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); tmElements_t tm; breakTime(alarmTime, tm); i2cBeginTransmission(RTC_ADDR); @@ -443,18 +446,18 @@ void MCP79412RTC::setAlarm(const ALARM_NBR_t alarmNumber, const uint16_t y, cons void MCP79412RTC::enableAlarm(const ALARM_NBR_t alarmNumber, const ALARM_TYPES_t alarmType) { uint8_t ctrl; // control register has alarm enable bits - ramRead(CONTROL, &ctrl, 1); + readRTC(CONTROL, &ctrl, 1); if (alarmType < ALM_DISABLE) { uint8_t day; // alarm day register has config & flag bits - ramRead(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + readRTC(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); day = ( day & 0x87 ) | alarmType << 4; // reset interrupt flag, OR in the config bits - ramWrite(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + writeRTC(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); ctrl |= _BV(ALM0EN + alarmNumber); // enable the alarm } else { ctrl &= ~(_BV(ALM0EN + alarmNumber)); // disable the alarm } - ramWrite(CONTROL, &ctrl, 1); + writeRTC(CONTROL, &ctrl, 1); } // Returns true or false depending on whether the given alarm has been @@ -463,10 +466,10 @@ void MCP79412RTC::enableAlarm(const ALARM_NBR_t alarmNumber, const ALARM_TYPES_t bool MCP79412RTC::alarm(const ALARM_NBR_t alarmNumber) { uint8_t day; // alarm day register has config & flag bits - ramRead( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + readRTC( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); if (day & _BV(ALMxIF)) { day &= ~_BV(ALMxIF); // turn off the alarm "interrupt" flag - ramWrite( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + writeRTC( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); return true; } else @@ -478,12 +481,12 @@ bool MCP79412RTC::alarm(const ALARM_NBR_t alarmNumber) void MCP79412RTC::out(const bool level) { uint8_t ctrlReg; - ramRead(CONTROL, &ctrlReg, 1); + readRTC(CONTROL, &ctrlReg, 1); if (level) ctrlReg |= _BV(OUT); else ctrlReg &= ~_BV(OUT); - ramWrite(CONTROL, &ctrlReg, 1); + writeRTC(CONTROL, &ctrlReg, 1); } // Specifies the logic level on the Multi-Function Pin (MFP) when an @@ -499,12 +502,12 @@ void MCP79412RTC::out(const bool level) void MCP79412RTC::alarmPolarity(const bool polarity) { uint8_t alm0Day; - ramRead(ALM0WKDAY, &alm0Day, 1); + readRTC(ALM0WKDAY, &alm0Day, 1); if (polarity) alm0Day |= _BV(ALMPOL); else alm0Day &= ~_BV(ALMPOL); - ramWrite(ALM0WKDAY, &alm0Day, 1); + writeRTC(ALM0WKDAY, &alm0Day, 1); } // Check to see if the RTC's oscillator is started (STOSC bit in seconds @@ -526,13 +529,13 @@ bool MCP79412RTC::isRunning() void MCP79412RTC::vbaten(const bool enable) { uint8_t day; - ramRead(RTCWKDAY, &day, 1); + readRTC(RTCWKDAY, &day, 1); if (enable) day |= _BV(VBATEN); else day &= ~_BV(VBATEN); - ramWrite(RTCWKDAY, &day, 1); + writeRTC(RTCWKDAY, &day, 1); return; } @@ -560,7 +563,7 @@ void MCP79412RTC::dumpRegs(const uint32_t startAddr, const uint32_t nBytes) uint32_t aLast {startAddr}; for (uint32_t r = 0; r < nRows; r++) { uint32_t a = startAddr + 16 * r; - ramRead(a, d, 16); + readRTC(a, d, 16); bool same {true}; for (int i=0; i<16; ++i) { if (last[i] != d[i]) same = false; diff --git a/src/MCP79412RTC.h b/src/MCP79412RTC.h index 7b4f70a..be050b6 100644 --- a/src/MCP79412RTC.h +++ b/src/MCP79412RTC.h @@ -22,6 +22,7 @@ #include #include // https://github.com/PaulStoffregen/Time +#include // define consistent I2C functions #if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) @@ -50,7 +51,7 @@ #define BUFFER_LENGTH 32 #endif -class MCP79412RTC +class MCP79412RTC : public GenericRTC { public: // Alarm types for use with the enableAlarm() function @@ -139,12 +140,12 @@ class MCP79412RTC ALMxMSK0 {4}, ALMxIF {3}; // Alarm Interrupt Flag: Set by hardware when an alarm was triggered, cleared by software. - MCP79412RTC(TwoWire& tw=Wire) : wire(tw) {}; + MCP79412RTC(TwoWire& tw=Wire) : GenericRTC{tw} {}; void begin(); time_t get(); - void set(const time_t t); + uint8_t set(const time_t t); bool read(tmElements_t& tm); - void write(const tmElements_t& tm); + uint8_t write(const tmElements_t& tm); void sramWrite(const uint8_t addr, const uint8_t value); void sramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); uint8_t sramRead(const uint8_t addr); @@ -172,12 +173,13 @@ class MCP79412RTC void dumpSRAM(const uint32_t startAddr=0, const uint32_t nBytes=64); void dumpEEPROM(const uint32_t startAddr=0, const uint32_t nBytes=128); + uint8_t writeRTC(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); + uint8_t writeRTC(const uint8_t addr, const uint8_t value); + uint8_t readRTC(const uint8_t addr, uint8_t* values, const uint8_t nBytes); + uint8_t readRTC(const uint8_t addr); + private: - TwoWire& wire; // reference to Wire, Wire1, etc. - void ramWrite(const uint8_t addr, const uint8_t value); - void ramWrite(const uint8_t addr, const uint8_t* values, const uint8_t nBytes); - uint8_t ramRead(uint8_t addr); - void ramRead(const uint8_t addr, uint8_t* values, const uint8_t nBytes); + //TwoWire& wire; // reference to Wire, Wire1, etc. uint8_t eepromWait(); uint8_t dec2bcd(const uint8_t num); uint8_t bcd2dec(const uint8_t num); From 2b90bb7ee40fb2b9152abc025132afd6203c77bf Mon Sep 17 00:00:00 2001 From: JChristensen Date: Tue, 24 Jun 2025 11:08:34 -0400 Subject: [PATCH 21/22] Update library.properties. --- library.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library.properties b/library.properties index e9a1a06..2a7811e 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=MCP79412RTC -version=3.0.0 +version=3.1.0 author=Jack Christensen maintainer=Jack Christensen sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. From 586ab3b12ca846942a7cfaedeae26dc40ec34740 Mon Sep 17 00:00:00 2001 From: JChristensen Date: Sat, 5 Jul 2025 16:31:17 -0400 Subject: [PATCH 22/22] Add temperature() method to the base class. --- library.properties | 2 +- src/GenericRTC.h | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/library.properties b/library.properties index 2a7811e..67380c8 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=MCP79412RTC -version=3.1.0 +version=3.1.1 author=Jack Christensen maintainer=Jack Christensen sentence=Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar. diff --git a/src/GenericRTC.h b/src/GenericRTC.h index 933651d..c0e009a 100644 --- a/src/GenericRTC.h +++ b/src/GenericRTC.h @@ -4,7 +4,7 @@ // Copyright (C) 2025 by Jack Christensen and licensed under // GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html // -// Allows a sketch to work with either type of RTC, determined at run time. +// Allows a sketch to work with either type of RTC, can be determined at run time. #ifndef GENERIC_RTC_H_INCLUDED #define GENERIC_RTC_H_INCLUDED @@ -20,10 +20,11 @@ class GenericRTC virtual void begin() = 0; virtual time_t get() = 0; virtual uint8_t set(const time_t t) = 0; - virtual uint8_t writeRTC(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) =0; + virtual uint8_t writeRTC(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) = 0; virtual uint8_t writeRTC(const uint8_t addr, const uint8_t value) = 0; virtual uint8_t readRTC(const uint8_t addr, uint8_t* values, const uint8_t nBytes) = 0; virtual uint8_t readRTC(const uint8_t addr) = 0; + virtual int16_t temperature() {return 0;}; protected: TwoWire& wire; // reference to Wire, Wire1, etc.