Skip to content

SetAndCalibrate.ino

Arnd edited this page Dec 11, 2020 · 4 revisions

Sample Arduino sketch to demonstrate setting, reading and calibrating an attached MCP7940 real time clock. While there is at present no breakout board for this chip, it is available as a PDIP 8-pin package which makes it easy to implement in a breadboard or solder onto a homemade project.. The MCP7940 uses I2C communication which means that only 2 wires are needed to the microprocessor. The MCP7940 does need 3 specific components to function, a 32.768kHz crystal and two small capacitors. The datasheet specifies what sort of a crystal and how to compute the sizing of the 2 capacitors, in my case I could use a crystal with 6pF capacitance and two 6.2pF capacitors on my breadboard.

Sample circuit

The image below shows the breadboard layout that I used for this sample program.

Program Overview

The sketch has been tested on Arduino Micro and ATMega 2560 and uses the serial port at 115200 baud. It starts off by initializing the serial interface and instantiates and initializes the MCP7940 with the date/time that the library was pre-compiled (note that this might be earlier than when the sketch was compiled, which can lead to confusion). The sketch makes use of the sprintf() function to print out the date/time since this function allows formatting leading zeroes, which the Serial.print() function does not. The program outputs the date/time to the display every second and also toggles the Arduino builtin LED every second. The date/time can be set by entering the command "SETDATE yyyy-mm-dd hh:nn:ss" in the serial monitor and sending it to the Arduino. The command is not case sensitive, but the date and time must be entered as shown above otherwise the command will be rejected. The program also accepts the command "CALDATE yyyy-mm-dd hh:nn:ss" which will perform a calibration.

Details

Calibration is somewhat difficult, as the RTC is generally quite accurate and it can take hours or days for the RTC to differ from the correct time by more than one second. But the sketch allows an exemplary calibration to be done; see the example sketch CalibrateFromGPS for an example of how to use a connected GPS device to continually monitor the date/time and to automatically set a calibration adjustment when a difference is detected.

Clone this wiki locally