Giter Club home page Giter Club logo

ds3231's Introduction

DS3231 Library

An Arduino library for the DS3231 real-time clock (RTC).

Description

The library provides easy-to-use methods to:

  • set and read the current date and time;
  • set, clear, and detect two, independent, Time-of-Day alarms;
  • perform certain conversions and calculations with time data;
  • manage certain hardware inside the DS3231 RTC module.

This document explains the installation and usage of the Library with the Arduino IDE.

You do have to install the Library in your Arduino IDE environment before you can use it. Installation instructions are provided, below.

Contents


Summary

After installing the Library in your Arduino IDE, using it in a program starts with three, simple steps:

  1. Import the Library into the program code:
#include <DS3231.h>
  1. Declare a DS3231 object, for example:
DS3231 myRTC;
  1. Start the Wire library to enable I2C communications with the DS3231 hardware, typically in the setup() code block:
Wire.begin();

Then, Library functions are typically accessed through the DS3231 object. For example, to read the current date of the month (1 through 28, 29, 30 or 31, depending on the month and the year):

unsigned int theDate = myRTC.getDate();

The Library incorporates two other classes to assist with managing date and time data:

  • DateTime enables a versatile object for managing date and time data. A variable of the DateTime type can represent a specific date and time in two different ways:
    1. as distinct values for year, month, day, hour, minute and second, or
    2. as a single, unsigned integer. The latter is handy for doing arithmetic with dates.
  • RTClib institutes a convenient RTClib::now() function for receiving a date/time snapshot, as a DateTime object, from the DS3231 device.

How to Cite

If you use this library in a publication, please cite it in one or both of the following two ways:

  1. Through the CITATION.cff file here, which should be up to date with the permanent archive available from Zenodo
  2. If you need an academic journal reference and/or you are discussing the integration of the DS3231 into a larger hardware + firmware ecosystem,
    Wickert, A. D., Sandell, C. T., Schulz, B., & Ng, G. H. C. (2019), Open-source Arduino-compatible data loggers designed for field research, Hydrology and Earth System Sciences, 23(4), 2065-2076, doi:10.5194/hess-23-2065-2019.
    This option should not be the only one used because it does not credit the original library developer, Eric Ayars.

About the DS3231

DS3231 is a low-cost integrated circuit (IC) providing a highly accurate, real time clock for use with Arduino, Raspberry Pi, BBC micro:bit and other popular small computing devices.

The IC is typically mounted on a circuit board or module, along with other hardware, such as header pins, supportive electrical components, and even EEPROM memory chips, for convenient attachment to a breadboard or an Arduino.

Several different modules are available from a number of competing vendors. This Library aspires to work with any DS3231 module that supports I2C communications with the IC.

DS3231 runs independently and can be kept running for a considerable length of time by a small, backup battery, even if power to the Arduino is turned off.

According to the datasheet, the DS3231 hardware "completely manages all timekeeping functions (including):

  • Seconds,
  • Minutes,
  • Hours
    • 12-hour format with AM/PM indication, or
    • 24-hour format,
  • Day of the Week,
  • Date of the Month,
  • Month, and
  • Year, with Leap-Year Compensation Valid Up to 2100"

Data for the time and date are stored in registers (memory locations) on the DS3231. Each, distinct value is stored separately. This means the seconds are in one register, the minutes in another, and so forth. The DS3231 updates the values in the date and time registers every second.

The device keeps track of time by operating its own 32.768 kHz crystal oscillator, similar to the timekeeper in an electronic watch. Temperature can affect oscillator speed. Accordingly, the DS3231 takes further steps to maintain accuracy. It senses the temperature around the crystal and adjusts the speed of the oscillator.

The oscillator can be accessed directly, independent of the date and time registers, for use as an external timer or source of interrupts.

The temperature can be read from the DS3231 using a Library function. The data sheet declares it to be accurate to within 3 degrees, Celsius.

Power Supply and Battery Backup

The DS3231 can run in a range between 2.3 volts and 5.5 volts. The device actually has two power supply pins: the primary source, VCC, and a secondary, backup source, VBAT.

Some popular modules mounting a DS3231 provide a receptacle for a coin battery, attaching it to the VBAT pin. If a sufficiently-charged battery is present, the DS3231 will switch automatically to the battery after detecting a drop in VCC voltage below a certain "power-fail" level.

It will switch back to VCC automatically, if and when that voltage rises back up above both the power-fail and the battery voltage level.

One point regarding the choice of battery may deserve consideration: the question of whether to install a rechargeable coin battery, or to disable a charging circuit if such a thing is provided on the module being used. The topic is controversial and the authors of this Library do not express any opinion about it. Readers may choose to search online for more information.

back to top


Installation

First Method

image

  1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries
  2. Then the Library Manager will open and you will find a list of libraries that are already installed or ready for installation.
  3. Then search for DS3231 using the search bar.
  4. Click on the text area and then select the specific version and install it.

Second Method

  1. Navigate to the Releases page.
  2. Download the latest release.
  3. Extract the zip file
  4. In the Arduino IDE, navigate to Sketch > Include Library > Add .ZIP Library

Dependencies

The user must also ensure that two, other, required libraries are available to the Arduino IDE. This DS3231 library takes care to #include the following in a program, but it does not install them in your Arduino IDE:

  • Wire.h : a widely-used Arduino library for I2C communications
  • time.h : a modified C language header file packaged with avr-libc and the AVR-GCC compiler

Note: At the time of writing, both of these libraries were included by default with a standard installation of the 1.8.x version of Arduino IDE for AVR-based devices.

A simple way to check for the availability of the two libraries is to compile the following, blank Arduino sketch. If the IDE does not complain that anything is missing, then the required libraries are available for use with this DS3231 library.

#include <Wire.h>
#include <time.h>
void setup() {}
void loop() {}

back to top


Functions

Readers are encouraged to visit the Documentation folder for detailed information about the functions in this Library. Additional information is available in the Examples of Use described below, and in the code source files of this repository:

* The RTClib::now() function is not accessed through the DS3231 object. Rather, it has a very specific syntax as described below in The Special RTClib::now() Function.

We emphasize here and elsewhere that the code writer bears responsibility to ensure that the values passed into the following functions fall within the valid range, as specified in the documentation for each function.

Unexpected values in the DS3231 hardware registers may follow from the insertion of an invalid parameter into any one of these functions.

The following functions set and retrieve time and date values in the DS3231 hardware alarm registers.

Parameters include a special 8-bit value named "AlarmBits". Readers may find additional information about it at the following links: Alarm Bits Quick Reference, and Alarm Bits in Detail.

The remaining functions in this group set and retrieve certain flags in the DS3231 hardware that govern or report the operation of the alarms.

The functions in this group support uses for a DS3231 other than as an alarm clock.

A limited DateTime class is defined in this DS3231.h library. The link, above, provides more information about the class.

Retrieving Date and Time Data further documents the DateTime class methods listed below.

  • year()
  • month()
  • day()
  • hour()
  • minute()
  • second()
  • unixtime()

The Special RTClib::now() Function

RTClib::now() is the precise, complete name for a special function that returns a DateTime object from the DS3231. Always write it just so: RTClib::now().

The function returns a DateTime object. To use it in your program, declare a DateTime type of variable to receive the value. For example,

DateTime currentMoment = RTClib::now();

The value of currentMoment can then be accessed as either:

  • an unsigned integer containing the number of seconds since a certain reference date, or
  • distinct values for Year, Month, Day, Date, Hour, Minute, or Second.

back to the list of functions
back to top


Examples of Use

There are many examples provided in the examples folder of this repository. At the time of writing the examples include:

  • set: demonstrates selected time-setting functions
  • test: demonstrates selected time-reading functions
  • echo: demonstrates setting the time and date then reading it back
  • echo_time: similar to echo, demonstrates setting and reading time/date data
  • oscillator_test: demonstrates advanced techniques for managing and using the DS3231 device as a pulse generator

Future development plans include updating these examples and adding more of them.

See also Working with the DS3231 libraries and interrupts, a tutorial provided by IowaDave.

back to top


Additional Resources and References

back to top


Contributing

If you want to contribute to this project:

  • Report bugs and errors
  • Ask for enhancements
  • Create issues and pull requests
  • Tell others about this library
  • Contribute new protocols

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

back to top


Credits

This is a splice of Ayars' and Jeelabs/Ladyada's libraries.

The authors of this library are A. Wickert [email protected], E. Ayars, J. C. Wippler, N. W. LLC [email protected] and it is maintained by A. Wickert. This library is released into the public domain by Jeelabs, Ladyada, and E. Ayars.

Based on previous work by:

  • S. T. Andersen
  • SimGas
  • Per1234
  • Glownt

back to top


License

DS3231 is licensed under The Unlicense.

back to top


To Do

A project is underway to update the library's documentation.

Existing Repo Issues to be addressed:

  • #42 Alarm Documentation
  • #24 DateTime Comparison Operators
  • #20 AlarmBits Documentation

ds3231's People

Contributors

aghasaad04 avatar asvoria avatar awickert avatar designer2k2 avatar easyg0ing1 avatar fabien-gigante avatar glownt avatar hasenradball avatar iowadave avatar jefferson-lopes avatar jnuernberg avatar johanneswilde avatar lucidm avatar mike-s123 avatar mrbesen avatar nuxeh avatar ostaquet avatar per1234 avatar photonphive avatar simgas avatar sthing avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ds3231's Issues

Documentation request : specify alarm AxM bits position

Hi,

would it be possible to add an information about the positions of the alarm bits used in functions setA1Time and setA2Time please (I don't know how to do it by my self, sorry).

Having a look inside the setA1Time and setA2Time code and the DS3231.pdf, the use of AlarmBits parameter is not obvious.

Could you specify something like this, whatever the function setA1Time or setA2Time used, the AlarmBits parameter bits are placed this way (b7 to b0) :
x A2M4 A2M3 A2M2 A1M4 A1M3 A1M2 A1M1

Those bits correspond to page12/20 of DS3231.pdf from www.maximintegrated.com file.

Thanks.

where are descriptions of the functions?

Sometimes I feel really stupid, like right now.. sorry, but I need to ask:
You write a lot of possible functions, but I can't find any description..?
I know I can open the examples and can find several functions but not all and not ordered.

RTC freezing and locking up

Battery powered RTC seems to be frozen after Arduino power up. The command RTC.now() is reporting 165:165:85 which does not make any sense. As the device is powered and battery is soldered, I am unable to cut its power.

Proposed solution: the class should provide a mechanism to control manually the logic level of the output digital pins to attempt to unlock the communication channel, e.g. the i2c bus is always "busy".

Added Changelog

This is not really an issue, so please close, when read!

Hi everyone, Hi @awickert,

I took the liberty and added a changlog to the master branch to keep track of changes, additions, etc, that go into future versions. With more people contributing, I hope to keep track of more recent changes.

The structure is rather simple: The changelog consists of a list of sections, one per version, latest first. Above the latest version section, there is a section for the next, upcoming version. Whenever there is an addition of a feature or a change in code (either through direct edits or through PRs), add the changes as a bullet point to the upcoming versions sections.

When ready for the next version, change the upcoming version section to the next build-version and introduce a new upcoming version.

Final note on the bullet points: Be precise and comprehensive, just like in your commit messages.

Best regards,
Jacob

add function documentation?

There does not appear to be any documentation for this library anywhere, which isn't great. There are examples, but that doesn't tell anyone what the function signatures are, what input they expect, and what output they yield. Can that be added? Also, as a splice of the Adafruit library, where are the initialized and adjust functions? Because those are incredibly useful =)

(being able to say rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); makes setting the RTC entirely trivial compared to having to call seven separate functions)

Not compiling

Not sure it is a bug.
i'm unable to compile "DS3231_set" example

error message
DS3231_set:13:8: error: 'DS3231 clock' redeclared as different kind of symbol
DS3231 clock;

Arduino uno R3
latest ide 1.8.19
win 7
DS3131 version 1.1.0

timestamt and unix time don't match

Hey, I use this library and wehen I set the time of the RTC ds3231 to the current time (UTC time zone) and afterwards ask for timestamp.hour()(minute()/seconds() and the unixtime() the unix time is offset compared to hours, minutes by 2 hours
can it be that the ds3231 can be set to a specific time zone and thereby gives me this offset?
thanks

Year 2106 potential problem?

Could the following method be vulnerable to the Year 2106 Problem, since it returns an unsigned int?
uint32_t unixtime(void) const;

Plus, I think for a unix timestamp, it should be given as an unsigned long.

No return value when failing to talk to the RTC

If the arduino boots up and the RTC is not connected, it will not return error values for some parameters such as date and time.

A simple fix is to add the following lines of code in every method:

if (!Wire.available())
{
    return 99; // Some obvious error value
}

For example in the getSecond() method:

byte DS3231::getSecond() {
    Wire.beginTransmission(CLOCK_ADDRESS);
    Wire.write(0x00);
    Wire.endTransmission();
    Wire.requestFrom(CLOCK_ADDRESS, 1);

        if (!Wire.available())
        {
            return 99; // Some obvious error value
        }

    return bcdToDec(Wire.read());
}

DS3231_test:16:8: error: 'DS3231 clock' redeclared as different kind of symbol DS3231 clock; ^~~~~

Hi,
I am trying to load this example Arduino on a Nano attached to a DS3231 RTC and it fails with these error messages. Is there an update available?

Using library DS3231 at version 1.1.0 in folder: S:\MyProject\AVR\Arduinosketchbook\libraries\DS3231
Using library Wire at version 1.0 in folder:
\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.5\libraries\Wire
exit status 1
'DS3231 clock' redeclared as different kind of symbol

Compile errors with recent getAXAlarm() and checkIfAlarm() overloads

Posting an issue here that I am working to understand and resolve.

Recent PRs added overloads to the functions for getAXAlarm() and checkIfAlarm().

I am encountering fatal errors during compilation of the library's .cpp file with these overloads. The compiler seems to fail to find the second, overloading prototype in the header file.

For example:

error: prototype for 'void DS3231::getA1Time(byte&, byte&, byte&, byte&, byte&, bool&, bool&, bool&, bool)' does not match any in class 'DS3231'
void DS3231::getA1Time(byte& A1Day, byte& A1Hour, byte& A1Minute, byte& A1Second, byte& AlarmBits, bool& A1Dy, bool& A1h12, bool& A1PM, bool clearAlarmBits) {
^~~~~~
error: candidate is: void DS3231::getA1Time(byte&, byte&, byte&, byte&, byte&, bool&, bool&, bool&)
void DS3231::getA1Time(byte& A1Day, byte& A1Hour, byte& A1Minute, byte& A1Second, byte& AlarmBits, bool& A1Dy, bool& A1h12, bool& A1PM) {
^~~~~~

AlarmBits parameter not initialized in getA1Time and getA2Time

I saw, that getA1Time and getA2Time do not clear parameter AlarmBits before setting certain bits there.
Probably they were written this way to facilitate combining the AlarmBits of these two functions when called in sequence.

Please add a note in DS3231.h, that variable AlarmBits needs to be cleared before calling getA1/2Time to avoid 'random' output.
Also clear that variable in DS3231_test.pde.
This may be a reason for issue #7 (Alarm 2 gives wrong Alarm bits back).

If combining the AlarmBits of A1 and A2 is not so important for you, you may want to change the first assignment of AlarmBits in getA1Time/getA2Time from
AlarmBits = AlarmBits | (temp_buffer & ...
to
AlarmBits = (temp_buffer & ...

Error compiling for board Seeeduino XIAO.

when i try to run examples/now/now.pde on my Seeeduino XIAO, i get the following error:

In file included from /Users/tlossen/Library/Arduino15/packages/Seeeduino/tools/CMSIS-Atmel/1.2.1/CMSIS-Atmel/CMSIS/Device/ATMEL/samd21/include/samd21.h:69:0,
                 from /Users/tlossen/Library/Arduino15/packages/Seeeduino/tools/CMSIS-Atmel/1.2.1/CMSIS-Atmel/CMSIS/Device/ATMEL/samd.h:105,
                 from /Users/tlossen/Library/Arduino15/packages/Seeeduino/tools/CMSIS-Atmel/1.2.1/CMSIS-Atmel/CMSIS/Device/ATMEL/sam.h:540,
                 from /Users/tlossen/Library/Arduino15/packages/Seeeduino/hardware/samd/1.8.1/cores/arduino/Arduino.h:49,
                 from sketch/rtc_now.ino.cpp:1:
/Users/tlossen/Library/Arduino15/packages/Seeeduino/tools/CMSIS-Atmel/1.2.1/CMSIS-Atmel/CMSIS/Device/ATMEL/samd21/include/samd21g18a.h:476:27: error: expected ',' or '...' before '(' token
 #define PM                ((Pm       *)0x40000400UL) /**< \brief (PM) APB Base Address */
                           ^
/Users/tlossen/Documents/Arduino/libraries/DS3231/DS3231.h:71:33: note: in expansion of macro 'PM'
   byte getHour(bool& h12, bool& PM);
                                 ^~
exit status 1
Error compiling for board Seeeduino XIAO.

it seems that the variable PM clashes with a macro defined for samd21 boards?

DateTime constructor crashes SAMD21

The following constructor caused a hard fault on a SAMD21 device:

DateTime (const char* date, const char* time);

The following minimal snippet illustrates the trouble:

#include <DS3231.h>
DateTime trouble("Jan 12 2023", "12:07:00");
void setup() {
  ;
}
void loop() {
  ;
}

Immediately after uploading, the device loses its Serial connection to the computer. The connection must be restored with a quick double-tap of the reset button before code can be uploaded again.

The other constructors, that use numeric parameters, do not cause this problem in a declaration statement. However, I might have seen a similar result when using the RTClib::now() function farther along in a program. Can't remember.

Perhaps DateTime should be approached with caution on SAMD21 hardware because this repo was written for 8-bit AVR chips. I wonder whether an attempt to read or write some memory location that is not 32-bit aligned may be causing a hard fault which hangs up the CPU.

In the interest of preserving compactness when compiled for AVRs, it may be desirable to create an alternate code body for DateTime to be compiled for the SAMD21G18A architecture. Putting this issue out there for the community to consider. Hope someone who knows the DateTime code intimately can address this issue with skill, before I try to wrap my amateurish hands around it.

David

OSF flag needs independent reset function.

Current the OSF flag is reset in setSeconds() and no other function is provided to do it. This seems like a bit of an arbitrary choice and has led to some unpredictable errors occurring for me where this flag was being reset without me knowing how. The documentation says it makes good housekeeping sense and perhaps that's true but surely that should the user should at least be given the choice?

I propose that:

  1. Clear OSF flag functionality should be removed from setSeconds().
  2. Clear OSF flag function be defined independently to perform this role.

Alarm 2 gives wrong Alarm bits back

Hi,

I discovered that Alarm 2 gives wrong alarm bits back when reading them. I'm not sure if the wrong bits are written to the controller or if just the reading is wrong. but I think its a combination of both problems.
Alarm 1 works totally fine

Cannot find any mention of which day of the week is 1

I checked the docs, the examples, the header, and the cpp file, and can find no mention of whether this library counts Monday or Sunday as doW 1. (Yes some people consider the week to start on Sunday while others consider it to start on Monday)

Does it matter? I don't know, but I can't find anything that says anything.

echo_time example file compile errors

First time using github, so apologies if this isn't in the format you'd expect; happy to take advice on improvements as necessary!

I've been trying to use the DS3231 Arduino library and decided to make a start with the "echo_time" example file as I believe my module still has a time inside it from when I used it some time ago. Upon doing so, I discovered that the example file cannot compile due to several errors, as follows:

  • Line 33: 'Century' is not declared in scope
  • Line 37: 'h12' is not declared in scope
  • Line 37: 'PM' is not declared in scope
  • Line 41/42: Missing '}' at the end of the for loop. Actual compile error points to line 44, but this is the cause.

For my general understanding of how these functions work, should the three variables simply need to be declared (as globals?) and 'passed' (as a pointer?) to the respective functions which will then change their value? Apologies if that's not the correct terminology!

Hope this helps.
Oli

DS3231 library getTemperature() function

Code using the DS3231 library was working until the library was updated. Is there something missing in nanf("")?

Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

/home/kraig/Arduino/libraries/DS3231/DS3231.cpp: In member function 'float DS3231::getTemperature()':
/home/kraig/Arduino/libraries/DS3231/DS3231.cpp:414:16: error: 'nanf' was not declared in this scope; did you mean 'tanf'?
414 | temp3231 = nanf(""); // Not a number
| ^~~~
| tanf
exit status 1
Error compiling for board Arduino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

New versions are not published to Arduino library manager

I can not see the version 1.1.1 in Arduino library description:

And also (probably because of that) I can not install it with arduino-cli - it installs version 1.1.0:

$ arduino-cli lib install DS3231
Downloading [email protected]...
[email protected] already downloaded
Installing [email protected]...
Installed [email protected]

While comparing version 1.1.0 and 1.1.1 I see that library.properties were not updated, but not sure what else is needed to make new version of this library. See also: #64 (comment).

I know that I can install the library by ZIP or GIT reference but it would be good if the newest version could be installed by Arduino IDE Library Manager:

DS3231

uninitialized const 'buff' [-fpermissive]

Hello,
tried to compile a sketch for MKRFOX1200 and got this error:
/Users/xxx/Documents/Arduino/libraries/DS3231-master/DS3231.cpp: In constructor 'DateTime::DateTime(const char*, const char*)'
/Users/xxx/Documents/Arduino/libraries/DS3231-master/DS3231.cpp:130:22: error: uninitialized const 'buff' [-fpermissive] static const char buff[4];

I added the initialization code and everything was fixed, please consider my PR ;)

Wrong text in DS3231/Documentation/Time-Retrieval.md

In that document, under the description of the getYear() function, there's a piece of text as follows:
_/*

  • returns: byte = 00 to 99
  • parameters: none
  • asserts: none
  • side effects: none
  • DS3231 register addressed: 0x06
    */

byte theDate = myRTC.getDate();_

Which no doubt should have been:

_/*

  • returns: byte = 00 to 99
  • parameters: none
  • asserts: none
  • side effects: none
  • DS3231 register addressed: 0x06
    */

byte theYear = myRTC.getYear();_

Gerard

DateTime comparison operators

Can we get '<', '>', '-', '+' operator overloading for the DateTime class?

I can submit a pull request to implement this if you like.

undefined reference to DateTime::dayOfTheWeek()

Hi everybody,

I'm using the DS3231 module and tried to modify the "now" example code:

void loop () {
    
    delay(1000);
    
    DateTime now = myRTC.now();
    
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    
    **Serial.print(now.dayOfTheWeek(), DEC);
    Serial.println();** 

but I got the error message
.../now/now.ino:37: undefined reference to DateTime::dayOfTheWeek() const`

what am I doing wrong? I use Arduno IDE 2.2.1 and DS33231 lib 1.1.2

Thank you
Marc

Just had it updated - stops compiling

There always were some minor notifications while compiling but now I get this:
Never mind. The update function "simply" pasted this library over another one i had installed....

No Alarm Documentation

I am working with DS3231's alarm programming and there is no documentation. Can someone explain what these parameters mean?

setA1Time(byte A1Day, byte A1Hour, byte A1Minute, byte A1Second, byte AlarmBits, bool A1Dy, bool A1h12, bool A1PM);

DateTime class accepts type-conflicting assignments

Requesting input from C++ experts regarding a puzzling behavior of the DateTime class as defined in this DS3231.h.

In Arduino IDE 1.8.15, at least, the following assignment ("=" operator) compiled and executed without error or any warning related to type mismatch between the LH and RH operands.

#include <DS3231.h>
DateTime myDT;
uint32_t arbitraryInteger = 42;

void setup() {
  myDT = arbitraryInteger;
  // ...moreover, to make it perfectly clear...
  myDT = 42;
}

Meaningless date and time values wwere retrieved from the DateTime instance following such an assignment.

Code writers using this library should exercise care to ensure that only sensible values are assigned to a DateTime instance.

My question for the community is whether -- and how -- the DateTime class can be defined in such a way that the Arduino IDE compiler will reject assignments of values, to a DateTime instance, that are of other, different, incompatible data types.

Update to 1.10. brocke compling, but it work with old library V1.0.7 !

Arduino: 1.8.17 Hourly Build 2021/09/06 02:34 (Mac OS X), Board: "ATmega2560, Yes (UART0), EEPROM retained, Arduino MEGA pinout, BOD 2.7V, LTO enabled, External 16 MHz"

/Users/name/Documents/Arduino/libraries/DS3231/DS3231.cpp: In constructor 'DateTime::DateTime(uint32_t)':
/Users/name/Documents/Arduino/libraries/DS3231/DS3231.cpp:104:18: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
if (days < 365 + leap)
~~~~~^~~~~~~~~~~~
/Users/name/Documents/Arduino/libraries/DS3231/DS3231.cpp: In member function 'void DS3231::setEpoch(time_t, bool)':
/Users/name/Documents/Arduino/libraries/DS3231/DS3231.cpp:264:12: error: aggregate 'DS3231::setEpoch(time_t, bool)::tm tmnow' has incomplete type and cannot be defined
struct tm tmnow;
^~~~~
/Users/name/Documents/Arduino/libraries/DS3231/DS3231.cpp:266:3: error: 'localtime_r' was not declared in this scope
localtime_r(&epoch, &tmnow);
^~~~~~~~~~~
/Users/name/Documents/Arduino/libraries/DS3231/DS3231.cpp:269:3: error: 'gmtime_r' was not declared in this scope
gmtime_r(&epoch, &tmnow);
^~~~~~~~
/Users/name/Documents/Arduino/libraries/DS3231/DS3231.cpp:269:3: note: suggested alternative: 'time_t'
gmtime_r(&epoch, &tmnow);
^~~~~~~~
time_t
Mehrere Bibliotheken wurden für "Timezone.h" gefunden
Benutzt: /Users/name/Documents/Arduino/libraries/Timezone
Nicht benutzt: /Users/name/Documents/Arduino/libraries/Timezone-master
Mehrere Bibliotheken wurden für "TimeLib.h" gefunden
Benutzt: /Users/name/Documents/Arduino/libraries/Time-master
Nicht benutzt: /Users/name/Documents/Arduino/libraries/Time
exit status 1
Fehler beim Kompilieren für das Board ATmega2560.

Dieser Bericht wäre detaillierter, wenn die Option
"Ausführliche Ausgabe während der Kompilierung"
in Datei -> Voreinstellungen aktiviert wäre.

INT/SQW pin stays LOW following triggered alarm

Once alarm is triggered method DS3231::turnOffAlarm(byte Alarm) does not reset A1F / A2F bits in status register 0x0F. This makes SQW pin stay LOW and thus making following interrupts impossible.

Simple solution would be to add following codes at the end of the method to modify status byte as well.

	// clear A1F/A2F flags for previously set alarms
	temp_buffer = readControlByte(1);
	// modify status byte
	if (Alarm == 1) {
		temp_buffer = temp_buffer & 0b11111110;
	} else {
		temp_buffer = temp_buffer & 0b11111101;
	}
	writeControlByte(temp_buffer, 1);

Thanks for the library!

Century "untouchable"

Hi,

Within DS3231.cpp, there is no possibility to update the "century" bit at adress 0x05h, bit 7.
You can read it with getMonth(&century) but using decToBcd(month) in the setMonth(month) routine doesn't allow to write it with for example setMonth( 0x80h OR month ).

A standalone function setCentury(bool Century) could be useful to complete the library :)

Yes... I know... the "century" bit is not very useful ;)

Best regards

no .begin

Compilation error: 'class DS3231' has no member named 'begin'

[Question]: get Epoch value from DS3231 possible?

Hi Andy,

I introduced a method 'setEpoch' to the DS3231 code.
Now I am thinking about to query the Epoch value back from the Ds3231 to feed the (for example) every hour the ESP8266.

Background is that the ESP8266 has ab very bad time accuracy, and want to feed it every hour by the Epoch queried from the RTC.

Is it possible to get the Epoch from the DS3231?

Checkifalarm issue

I encountered a problem when using the checkifalarm function. This function gives some issues, since my arduino code is only checking the alarms constantly and not doing anything else,

In the function the flags are red and then reset to 0, even when the flag isn't 1. This is problematic, since my code is nearly all of the time in the checkifalarm function. First the controlbyte is red out in this function, and the flag can be red as zero. In the meanwhile the flag can be set to 1 by the chip, but the code will still set the flag to zero. So the alarm is never triggered. This can easily be solved by the following code change:

bool DS3231::checkIfAlarm(byte Alarm) {
	// Checks whether alarm 1 or alarm 2 flag is on, returns T/F accordingly.
	// Turns flag off, also.
	// defaults to checking alarm 2, unless Alarm == 1.
	byte result;
	byte temp_buffer = readControlByte(1);
	if (Alarm == 1) {
		// Did alarm 1 go off?
		result = temp_buffer & 0b00000001;
		// clear flag
		if (result == 1)
		{
			temp_buffer = temp_buffer & 0b11111110;
			writeControlByte(temp_buffer, 1);
		}
	} else {
		// Did alarm 2 go off?
		result = temp_buffer & 0b00000010;
		// clear flag
		if (result == 0b10)
		{
			temp_buffer = temp_buffer & 0b11111101;
			writeControlByte(temp_buffer, 1);
		}
	}
	return result;
}

I don't know if this is the right place to put it, I am just new on Github. But please take a close look at it.

Teensy 4.0 Warning and unresponsive

C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp: In constructor 'DateTime::DateTime(const char*, const char*)':
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:132:41: warning: writing into constant object (argument 3) [-Wformat=]
sscanf(date, "%s %d %d", buff, &d, &y);
^
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:132:41: warning: format '%d' expects argument of type 'int*', but argument 4 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:132:41: warning: writing into constant object (argument 3) [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:132:41: warning: format '%d' expects argument of type 'int*', but argument 4 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:135:42: warning: format '%d' expects argument of type 'int*', but argument 3 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
sscanf(time, "%d:%d:%d", &hh, &mm, &ss);
^
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:135:42: warning: format '%d' expects argument of type 'int*', but argument 4 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:135:42: warning: format '%d' expects argument of type 'int*', but argument 5 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:135:42: warning: format '%d' expects argument of type 'int*', but argument 3 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:135:42: warning: format '%d' expects argument of type 'int*', but argument 4 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:135:42: warning: format '%d' expects argument of type 'int*', but argument 5 has type 'uint8_t* {aka unsigned char*}' [-Wformat=]
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp: In member function 'byte DS3231::getMonth(bool&)':
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:244:7: warning: unused variable 'hour' [-Wunused-variable]
byte hour;
^
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp: At global scope:
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:138:16: warning: 'uint8_t conv2d(const char*)' defined but not used [-Wunused-function]
static uint8_t conv2d(const char* p) {
^
C:\Users\admin\Documents\Arduino\libraries\DS3231\DS3231.cpp:158:16: warning: 'uint8_t bin2bcd(uint8_t)' defined but not used [-Wunused-function]
static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); }
#44

[Question]: Why do we use yOff instead use the Year In DateTime?

@awickert @IowaDave

Why do we use the yOff instead using the hole year number (e.g. 2023) in the DateTime Class?
Is ist possible to switch to use the year?

I would sugest to switch to

uint16_t year

as Data member for DateTime so no year information is lost.

Or maybee better to add the full year as Data member.
To be able to recalculate timesstanps in a way.

I could provide a solution.

Leap year calculation incorrect

The leap year calculation is currently set to y % 4 == 0. The correct logic to determine a leap year is y % 4 == 0 && (y % 100 > 0 || y % 400 == 0). Every 4 years is a leap year except centuries, unless the year is divisible by 400. I.E. 2000 was a leap year, 1900 and 2100 are not.

Possible to add sketch to adjust Aging Register?

My DS3231 loses a couple of secs/day. Research revealed the existence of an 'AgingRegister'. I'm not a C/C++ programmer, just a continually learning 'Arduino' progarmmer and so far I've not learned how to use it after reading many threads and browsing several DS3231 libraries.

I'd guess many users at a similar skill level would benefit from an Example sketch or independent function that allowed simple adustment of this register. Trial and error could then restore tolerable accuracy.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.