diff --git a/.gitignore b/.gitignore index 484b17a..8cb3738 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -ReadMe.txt +ReadMe.txt 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 . diff --git a/MCP79412RTC.cpp b/MCP79412RTC.cpp deleted file mode 100644 index f29d3b4..0000000 --- a/MCP79412RTC.cpp +++ /dev/null @@ -1,646 +0,0 @@ -/*----------------------------------------------------------------------* - * 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 -#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 -#elif ARDUINO >= 100 -#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 -#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 - -/*----------------------------------------------------------------------* - * Constructor. * - *----------------------------------------------------------------------*/ -MCP79412RTC::MCP79412RTC() -{ - 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) -{ - tmElements_t tm; - - if ( read(tm) ) - return( makeTime(tm) ); - else - return 0; -} - -/*----------------------------------------------------------------------* - * Set the RTC to the given time_t value. * - *----------------------------------------------------------------------*/ -void MCP79412RTC::set(time_t t) -{ - tmElements_t tm; - - breakTime(t, tm); - 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) -{ - i2cBeginTransmission(RTC_ADDR); - i2cWrite((uint8_t)TIME_REG); - if (i2cEndTransmission() != 0) { - return false; - } - else { - //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.Day = bcd2dec(i2cRead()); - 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. * - *----------------------------------------------------------------------*/ -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(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.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) - i2cEndTransmission(); -} - -/*----------------------------------------------------------------------* - * 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). * - *----------------------------------------------------------------------*/ -void MCP79412RTC::ramWrite(byte addr, byte *values, byte nBytes) -{ - i2cBeginTransmission(RTC_ADDR); - i2cWrite(addr); - for (byte i=0; i= 1 && (addr + nBytes) <= SRAM_SIZE) { -#else - if (nBytes >= 1 && nBytes <= (BUFFER_LENGTH - 1) && (addr + nBytes) <= SRAM_SIZE) { -#endif - ramWrite( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes ); - } -} - -/*----------------------------------------------------------------------* - * Read a single byte from Static RAM. * - * Address (addr) is constrained to the range (0, 63). * - *----------------------------------------------------------------------*/ -byte MCP79412RTC::sramRead(byte addr) -{ - byte value; - - ramRead( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, &value, 1 ); - return value; -} - -/*----------------------------------------------------------------------* - * Read multiple bytes from Static RAM. * - * Address (addr) is constrained to the range (0, 63). * - * Number of bytes (nBytes) must be between 1 and 32 (Wire library * - * limitation). * - * 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) -{ -#if defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) - if (nBytes >= 1 && (addr + nBytes) <= SRAM_SIZE) { -#else - if (nBytes >= 1 && nBytes <= BUFFER_LENGTH && (addr + nBytes) <= SRAM_SIZE) { -#endif - ramRead((addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes); - } -} - -/*----------------------------------------------------------------------* - * Write a single byte to EEPROM. * - * 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) -{ - i2cBeginTransmission(EEPROM_ADDR); - i2cWrite( addr & (EEPROM_SIZE - 1) ); - i2cWrite(value); - i2cEndTransmission(); - eepromWait(); -} - -/*----------------------------------------------------------------------* - * Write a page (or less) to EEPROM. An EEPROM page is 8 bytes. * - * Address (addr) should be a page start address (0, 8, ..., 120), but * - * 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) -{ - 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) { -#else - if (nBytes >= 1 && nBytes <= BUFFER_LENGTH && (addr + nBytes) <= EEPROM_SIZE) { -#endif - 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); - if (value < 0) calibVal += 128; - ramWrite(CALIB_REG, calibVal); - } -} - -/*----------------------------------------------------------------------* - * 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); - i2cWrite(UNIQUE_ID_ADDR); - i2cEndTransmission(); - i2cRequestFrom( EEPROM_ADDR, UNIQUE_ID_SIZE ); - for (byte i=0; i *powerUp) { - --dn.Year; - *powerDown = makeTime(dn); - } - return true; - } - else - return false; -} - -/*----------------------------------------------------------------------* - * Enable or disable the square wave output. * - *----------------------------------------------------------------------*/ -void MCP79412RTC::squareWave(uint8_t freq) -{ - uint8_t ctrlReg; - - ramRead(CTRL_REG, &ctrlReg, 1); - if (freq > 3) { - ctrlReg &= ~_BV(SQWE); - } - else { - ctrlReg = (ctrlReg & 0xF8) | _BV(SQWE) | freq; - } - ramWrite(CTRL_REG, &ctrlReg, 1); -} - -/*----------------------------------------------------------------------* - * 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 - - 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( (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. * - *----------------------------------------------------------------------*/ -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 - - 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 - ramWrite(ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); - ctrl |= _BV(ALM0 + alarmNumber); //enable the alarm - } - else { - 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) -{ - 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 - ramWrite( ALM0_DAY + alarmNumber * (ALM1_REG - ALM0_REG), &day, 1); - return true; - } - else - 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) -{ - uint8_t ctrlReg; - - ramRead(CTRL_REG, &ctrlReg, 1); - if (level) - ctrlReg |= _BV(OUT); - else - ctrlReg &= ~_BV(OUT); - 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) -{ - uint8_t alm0Day; - - ramRead(ALM0_DAY, &alm0Day, 1); - if (polarity) - alm0Day |= _BV(OUT); - else - alm0Day &= ~_BV(OUT); - 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) -{ - i2cBeginTransmission(RTC_ADDR); - i2cWrite((uint8_t)TIME_REG); - i2cEndTransmission(); - - //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) -{ - uint8_t day; - - ramRead(DAY_REG, &day, 1); - if (enable) - day |= _BV(VBATEN); - else - day &= ~_BV(VBATEN); - - ramWrite(DAY_REG, &day, 1); - return; -} - -/*----------------------------------------------------------------------* - * Decimal-to-BCD conversion * - *----------------------------------------------------------------------*/ -uint8_t MCP79412RTC::dec2bcd(uint8_t n) -{ - return n + 6 * (n / 10); -} - -/*----------------------------------------------------------------------* - * 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 - diff --git a/MCP79412RTC.h b/MCP79412RTC.h deleted file mode 100644 index edee9ad..0000000 --- a/MCP79412RTC.h +++ /dev/null @@ -1,133 +0,0 @@ -/*----------------------------------------------------------------------* - * 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. * - *----------------------------------------------------------------------*/ - -#ifndef MCP79412RTC_h -#define MCP79412RTC_h -#include - -#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 - -//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}; - -//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. -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 -#define ALARM_1 1 - -class MCP79412RTC -{ - public: - MCP79412RTC(); - static time_t get(void); - static void set(time_t t); - static boolean 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); - void calibWrite(int value); - void idRead(byte *uniqueID); - void getEUI64(byte *uniqueID); - boolean 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); - - 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 uint8_t dec2bcd(uint8_t num); - static uint8_t bcd2dec(uint8_t num); -}; - -extern MCP79412RTC RTC; - -#endif - diff --git a/ReadMe.md b/README.md similarity index 63% rename from ReadMe.md rename to README.md index 950a12c..dd91b8c 100644 --- a/ReadMe.md +++ b/README.md @@ -1,78 +1,150 @@ -# Arduino MCP79412 RTC Library v1.0 # +# Arduino MCP79412 RTC Library https://github.com/JChristensen/MCP79412RTC -ReadMe file -Jack Christensen Sep 2012 +README file +Jack Christensen +May 2025 -![CC BY-SA](http://mirrors.creativecommons.org/presskit/buttons/80x15/png/by-sa.png) +## License +Arduino MCP79412 RTC Library Copyright (C) 2012-2025 byJack Christensen GNU GPL v3.0 -## 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). +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. -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 `. +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 also implements methods to support the additional features of the MCP7941x RTC. +You should have received a copy of the GNU General Public License along with this program. If not, see + +## 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.) + - 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. -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 ## +## 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. +- **rtc_wire1:** Raspberry Pi Pico example using `Wire1`. - **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. +- **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. -## 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: +## 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 + +### 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(TwoWire& wire) +##### Description +Instantiates an `MCP79412RTC` object. +##### Syntax +`MCP79412RTC myRTC(wire);` +##### Parameters +**wire:** An optional parameter to specify which I2C bus to use. If omitted, defaults to `Wire`. *(TwoWire&)* +##### Returns +None. +##### Example ```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) +MCP79412RTC myRTC; // to use Wire +// or +MCP79412RTC myRTC(Wire1); // to use Wire1 + ``` -## Methods for setting and reading the time ## +## 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(); +} +``` -###get(void) -#####Description +## 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.). -#####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 +153,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 -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 +### 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](https://www.arduino.cc/playground/Code/Time) for details on the *tmElements_t* structure. +##### 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 +173,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 +194,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() +##### 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,263 +211,262 @@ 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. +## 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 +``` -###sramWrite(byte addr, byte value) -#####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 +`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. + +### 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 ## -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. -###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 ## -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 methods ## - -###calibWrite(int value) -#####Description +## 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. -#####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() +##### Description Reads the RTC calibration register. -#####Syntax -`RTC.calibRead(void);` -#####Parameters +##### Syntax +`RTC.calibRead();` +##### 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 +474,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 +490,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/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); - diff --git a/examples/PowerOutageLogger/PowerOutageLogger.ino b/examples/PowerOutageLogger/PowerOutageLogger.ino new file mode 100644 index 0000000..a4a528e --- /dev/null +++ b/examples/PowerOutageLogger/PowerOutageLogger.ino @@ -0,0 +1,198 @@ +// 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. +// 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 // https://github.com/janelia-arduino/Streaming +#include // https://github.com/JChristensen/Timezone + +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([](){return myRTC.get();}); // the function to get the time from the RTC + Serial << "RTC SYNC"; + if (timeStatus()!= timeSet) Serial << " FAIL"; + Serial << endl; + + 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 once a minute so that something is happening. + static time_t lastUTC; + time_t utc = now(); + if (minute(utc) != minute(lastUTC)) { + lastUTC = utc; + 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() { + 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 + + 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++) { + Serial << (uniqueID.b[i] < 16 ? " 0" : " ") << _HEX(uniqueID.b[i]); + } + Serial << endl; + + 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 + 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 += outageLength; + if (nextOutage > lastOutageAddr) nextOutage = firstOutageAddr; + myRTC.sramWrite(nextOutageAddr, nextOutage); + if (nOutage < maxOutages) myRTC.sramWrite(nbrOutagesAddr, ++nOutage); + } + + // print out all the outages logged + 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 -= outageLength; + if (outageAddr < firstOutageAddr) outageAddr = lastOutageAddr; + } +} + +// 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 +// 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 -void setup(void) +#include // https://github.com/JChristensen/MCP79412RTC +#include // http://arduiniana.org/libraries/streaming/ + +MCP79412RTC myRTC; + +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(RTC.get); + Serial << F( "\n" __FILE__ "\n" __DATE__ " " __TIME__ "\n" ); + myRTC.begin(); + + // setSyncProvider() causes the Time library to synchronize with the + // external RTC by calling myRTC.get() every five minutes by default. + setSyncProvider([](){return 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'; @@ -60,38 +57,54 @@ void setup(void) } 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'; Serial << _HEX(rtcID[i]); } Serial << endl; - - Serial << F("Calibration Register = ") << RTC.calibRead() << endl; + + Serial << F("Calibration Register = ") << myRTC.calibRead() << endl; } -void loop(void) +void loop() { + // check for input, to set rtc time or calibration + if (Serial.available()) setRTC(); + + // print time and date every second static time_t tLast; - time_t t; - tmElements_t tm; - int cmdChar, y, oldCal, newCal; + 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(); - //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. - y = Serial.parseInt(); + 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. + 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) @@ -101,70 +114,52 @@ void loop(void) 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 - setTime(t); - Serial << F("RTC set to: "); - printDateTime(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 = RTC.calibRead(); - 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; - } + 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; - //dump any extraneous input - while (Serial.available() > 0) Serial.read(); - } - - t = now(); - if (t != tLast) { - tLast = t; - printDateTime(t); - Serial << endl; + default: + Serial << endl << F("Unrecognized command: ") << (char)cmdChar << endl; + break; } -} -//print date and time to Serial -void printDateTime(time_t t) -{ - printDate(t); - Serial << ' '; - printTime(t); + // dump any extraneous input + while (Serial.available()) Serial.read(); } -//print time to Serial -void printTime(time_t t) +// format and print a time_t value +void printTime(const time_t t) { - printI00(hour(t), ':'); - printI00(minute(t), ':'); - printI00(second(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); } - -//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; -} \ No newline at end of file diff --git a/examples/TimeRTC/TimeRTC.ino b/examples/TimeRTC/TimeRTC.ino new file mode 100644 index 0000000..eebb75c --- /dev/null +++ b/examples/TimeRTC/TimeRTC.ino @@ -0,0 +1,49 @@ +// Arduino MCP79412RTC Library +// https://github.com/JChristensen/MCP79412RTC +// TimeRTC.ino +// Example sketch showing basic usage. + +#include // http://github.com/JChristensen/MCP79412RTC + +MCP79412RTC myRTC; + +void setup() +{ + myRTC.begin(); + Serial.begin(115200); + 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() +{ + digitalClockDisplay(); + delay(1000); +} + +// digital clock display of the time +void digitalClockDisplay() +{ + 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) +{ + 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/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 new file mode 100644 index 0000000..4725957 --- /dev/null +++ b/examples/rtcSet1/rtcSet1.ino @@ -0,0 +1,65 @@ +// 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 + +MCP79412RTC myRTC; + +void setup() +{ + myRTC.begin(); + delay(2000); + Serial.begin(115200); + + 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); + + myRTC.set(now()); // set the RTC from the system time + + // sync the system time with the RTC every five minutes (by default) + setSyncProvider([](){return myRTC.get();}); + if (timeStatus() != timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set 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..930b3cb --- /dev/null +++ b/examples/rtcSet2/rtcSet2.ino @@ -0,0 +1,53 @@ +// 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 + +MCP79412RTC myRTC; +tmElements_t tm; + +void setup() +{ + myRTC.begin(); + delay(2000); + Serial.begin(115200); + + tm.Hour = 23; // set the tm structure to 23h31m30s on 27Apr2022 + tm.Minute = 31; + tm.Second = 30; + 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 + myRTC.write(tm); // set the RTC from the tm structure +} + +void loop() +{ + myRTC.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..11f3295 --- /dev/null +++ b/examples/rtcSet3/rtcSet3.ino @@ -0,0 +1,79 @@ +// 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 + +MCP79412RTC myRTC; +time_t compileTime(const uint32_t fudge=10); // function prototype + +void setup() +{ + myRTC.begin(); + delay(2000); + Serial.begin(115200); + + setTime(compileTime()); // set the system time to the sketch compile time + myRTC.set(now()); // set the RTC from the system time +} + +void loop() +{ + printTime(now()); + delay(1000); +} + +// 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(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; + 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.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/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/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 2d9a19f..5aa9300 100644 --- a/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino +++ b/examples/tiny79412_KnockBang/tiny79412_KnockBang.ino @@ -1,44 +1,47 @@ -/*----------------------------------------------------------------------* - * 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 +// +// 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 +// 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) +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() causes the Time library to synchronize with the + // external RTC by calling RTC.get() every five minutes by default. + setSyncProvider([](){return myRTC.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 +53,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 +61,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 +69,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 +77,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/keywords.txt b/keywords.txt index eb42a60..228fac4 100644 --- a/keywords.txt +++ b/keywords.txt @@ -1,4 +1,8 @@ +# datatypes MCP79412RTC KEYWORD1 + +# methods & functions +begin KEYWORD2 get KEYWORD2 set KEYWORD2 read KEYWORD2 @@ -10,6 +14,7 @@ eepromRead KEYWORD2 calibRead KEYWORD2 calibWrite KEYWORD2 idRead KEYWORD2 +getEUI64 KEYWORD2 powerFail KEYWORD2 squareWave KEYWORD2 setAlarm KEYWORD2 @@ -18,3 +23,63 @@ alarm KEYWORD2 out KEYWORD2 alarmPolarity KEYWORD2 isRunning KEYWORD2 +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 new file mode 100644 index 0000000..67380c8 --- /dev/null +++ b/library.properties @@ -0,0 +1,10 @@ +name=MCP79412RTC +version=3.1.1 +author=Jack Christensen +maintainer=Jack Christensen +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=* +depends=Time diff --git a/src/GenericRTC.h b/src/GenericRTC.h new file mode 100644 index 0000000..c0e009a --- /dev/null +++ b/src/GenericRTC.h @@ -0,0 +1,32 @@ +// 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, can be 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; + virtual int16_t temperature() {return 0;}; + + protected: + TwoWire& wire; // reference to Wire, Wire1, etc. +}; +#endif diff --git a/src/MCP79412RTC.cpp b/src/MCP79412RTC.cpp new file mode 100644 index 0000000..7392e6b --- /dev/null +++ b/src/MCP79412RTC.cpp @@ -0,0 +1,666 @@ +// 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. + +#include + +// 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() +{ + tmElements_t tm; + + if ( read(tm) ) + return( makeTime(tm) ); + else + return 0; +} + +// Set the RTC to the given time_t value. +// Returns the I2C status (zero if successful). +uint8_t MCP79412RTC::set(const time_t t) +{ + tmElements_t tm; + + breakTime(t, tm); + return ( 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). +bool MCP79412RTC::read(tmElements_t& tm) +{ + i2cBeginTransmission(RTC_ADDR); + 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(STOSC)); + tm.Minute = bcd2dec(i2cRead()); + tm.Hour = bcd2dec(i2cRead() & ~_BV(HR1224)); // assumes 24hr clock + tm.Wday = i2cRead() & ~(_BV(OSCRUN) | _BV(PWRFAIL) | _BV(VBATEN)); // mask off OSCRUN, PWRFAIL, VBATEN bits + tm.Day = bcd2dec(i2cRead()); + tm.Month = bcd2dec(i2cRead() & ~_BV(LPYR)); // mask off the leap year bit + tm.Year = y2kYearToTm(bcd2dec(i2cRead())); + return true; + } +} + +// Set the RTC's time from a tmElements_t structure. +uint8_t MCP79412RTC::write(const tmElements_t& tm) +{ + i2cBeginTransmission(RTC_ADDR); + 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 + i2cWrite(dec2bcd(tm.Day)); + i2cWrite(dec2bcd(tm.Month)); + i2cWrite(dec2bcd(tmYearToY2k(tm.Year))); + i2cEndTransmission(); + + i2cBeginTransmission(RTC_ADDR); + i2cWrite(RTCSEC); + i2cWrite(dec2bcd(tm.Second) | _BV(STOSC)); // set the seconds and start the oscillator (Bit 7, STOSC == 1) + uint8_t ret = i2cEndTransmission(); + return ret; +} + +// Write a single byte to RTC RAM. +// Valid address range is 0x00 - 0x5F, no checking. +uint8_t MCP79412RTC::writeRTC(const uint8_t addr, const uint8_t value) +{ + 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). +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 && (addr + nBytes) <= SRAM_SIZE) { +#else + if (nBytes >= 1 && nBytes <= (BUFFER_LENGTH - 1) && (addr + nBytes) <= SRAM_SIZE) { +#endif + writeRTC( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes ); + } +} + +// Read a single byte from Static RAM. +// Address (addr) is constrained to the range (0, 63). +uint8_t MCP79412RTC::sramRead(const uint8_t addr) +{ + uint8_t value; + + readRTC( (addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, &value, 1 ); + return value; +} + +// Read multiple bytes from Static RAM. +// Address (addr) is constrained to the range (0, 63). +// Number of bytes (nBytes) must be between 1 and 32 (Wire library +// limitation). +// 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(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) { +#else + if (nBytes >= 1 && nBytes <= BUFFER_LENGTH && (addr + nBytes) <= SRAM_SIZE) { +#endif + readRTC((addr & (SRAM_SIZE - 1) ) + SRAM_START_ADDR, values, nBytes); + } +} + +// Write a single byte to EEPROM. +// 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(const uint8_t addr, const uint8_t value) +{ + i2cBeginTransmission(EEPROM_ADDR); + i2cWrite( addr & (EEPROM_SIZE - 1) ); + i2cWrite(value); + i2cEndTransmission(); + eepromWait(); +} + +// Write a page (or less) to EEPROM. An EEPROM page is 8 bytes. +// Address (addr) should be a page start address (0, 8, ..., 120), but +// 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(const uint8_t addr, const uint8_t* values, const uint8_t nBytes) +{ + if (nBytes >= 1 && nBytes <= EEPROM_PAGE_SIZE) { + i2cBeginTransmission(EEPROM_ADDR); + i2cWrite( addr & ~(EEPROM_PAGE_SIZE - 1) & (EEPROM_SIZE - 1) ); + for (uint8_t i=0; i= 1 && (addr + nBytes) <= EEPROM_SIZE) { +#else + if (nBytes >= 1 && nBytes <= BUFFER_LENGTH && (addr + nBytes) <= EEPROM_SIZE) { +#endif + i2cBeginTransmission(EEPROM_ADDR); + i2cWrite( addr & (EEPROM_SIZE - 1) ); + i2cEndTransmission(); + i2cRequestFrom(EEPROM_ADDR, nBytes); + for (uint8_t i=0; i= -127 && value <= 127) { + uint8_t calibVal = abs(value); + if (value < 0) calibVal += 128; + writeRTC(OSCTRIM, calibVal); + } +} + +// 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(uint8_t* uniqueID) +{ + i2cBeginTransmission(EEPROM_ADDR); + i2cWrite(UNIQUE_ID_ADDR); + i2cEndTransmission(); + i2cRequestFrom( EEPROM_ADDR, UNIQUE_ID_SIZE ); + for (uint8_t i=0; i *powerUp) { + --dn.Year; + *powerDown = makeTime(dn); + } + return true; + } + else + return false; +} + +// Enable or disable the square wave output. +void MCP79412RTC::squareWave(const SQWAVE_FREQS_t freq) +{ + uint8_t ctrlReg; + readRTC(CONTROL, &ctrlReg, 1); + if (freq > 3) { + ctrlReg &= ~_BV(SQWEN); + } + else { + ctrlReg = (ctrlReg & 0xF8) | _BV(SQWEN) | freq; + } + writeRTC(CONTROL, &ctrlReg, 1); +} + +// 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 + readRTC( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + tmElements_t tm; + breakTime(alarmTime, tm); + i2cBeginTransmission(RTC_ADDR); + 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( (day & 0xF8) + tm.Wday ); + i2cWrite(dec2bcd(tm.Day)); + i2cWrite(dec2bcd(tm.Month)); + 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(const ALARM_NBR_t alarmNumber, const ALARM_TYPES_t alarmType) +{ + uint8_t ctrl; // control register has alarm enable bits + readRTC(CONTROL, &ctrl, 1); + if (alarmType < ALM_DISABLE) { + uint8_t day; // alarm day register has config & flag bits + readRTC(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + day = ( day & 0x87 ) | alarmType << 4; // reset interrupt flag, OR in the config bits + writeRTC(ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + ctrl |= _BV(ALM0EN + alarmNumber); // enable the alarm + } + else { + ctrl &= ~(_BV(ALM0EN + alarmNumber)); // disable the alarm + } + writeRTC(CONTROL, &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. +bool MCP79412RTC::alarm(const ALARM_NBR_t alarmNumber) +{ + uint8_t day; // alarm day register has config & flag bits + readRTC( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + if (day & _BV(ALMxIF)) { + day &= ~_BV(ALMxIF); // turn off the alarm "interrupt" flag + writeRTC( ALM0WKDAY + alarmNumber * (ALM1SEC - ALM0SEC), &day, 1); + return true; + } + else + 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(const bool level) +{ + uint8_t ctrlReg; + readRTC(CONTROL, &ctrlReg, 1); + if (level) + ctrlReg |= _BV(OUT); + else + ctrlReg &= ~_BV(OUT); + writeRTC(CONTROL, &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(const bool polarity) +{ + uint8_t alm0Day; + readRTC(ALM0WKDAY, &alm0Day, 1); + if (polarity) + alm0Day |= _BV(ALMPOL); + else + alm0Day &= ~_BV(ALMPOL); + writeRTC(ALM0WKDAY, &alm0Day, 1); +} + +// 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(RTCSEC); + i2cEndTransmission(); + + // request just the seconds register + i2cRequestFrom(RTC_ADDR, static_cast(1)); + return i2cRead() & _BV(STOSC); +} + +// 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(const bool enable) +{ + uint8_t day; + readRTC(RTCWKDAY, &day, 1); + if (enable) + day |= _BV(VBATEN); + else + day &= ~_BV(VBATEN); + + writeRTC(RTCWKDAY, &day, 1); + return; +} + +// Decimal-to-BCD conversion +uint8_t MCP79412RTC::dec2bcd(const uint8_t n) +{ + return n + 6 * (n / 10); +} + +// BCD-to-Decimal conversion +uint8_t __attribute__ ((noinline)) MCP79412RTC::bcd2dec(const uint8_t n) +{ + return n - 6 * (n >> 4); +} + +// 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(const uint32_t startAddr, const 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; + readRTC(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(const uint32_t startAddr, const 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(const uint32_t startAddr, const 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 new file mode 100644 index 0000000..be050b6 --- /dev/null +++ b/src/MCP79412RTC.h @@ -0,0 +1,188 @@ +// 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_INCLUDED +#define MCP79412RTC_H_INCLUDED + +#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__) +#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 + +#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 + +class MCP79412RTC : public GenericRTC +{ + public: + // 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 + 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 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 + 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 + 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. + 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(TwoWire& tw=Wire) : GenericRTC{tw} {}; + void begin(); + time_t get(); + uint8_t set(const time_t t); + bool read(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); + 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(const int16_t value); + void idRead(uint8_t* uniqueID); + void getEUI64(uint8_t* uniqueID); + bool powerFail(time_t* powerDown, time_t* powerUp); + 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(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); + + 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. + uint8_t eepromWait(); + uint8_t dec2bcd(const uint8_t num); + uint8_t bcd2dec(const uint8_t num); +}; + +#endif