Saturday, December 17, 2011

Wise Clock 4 - Using the RTC 1Hz "Heartbeat"

DS3231 can generate a square wave output signal through pin 3 (aptly named "SQW"). Same pin can be also activated (set low) when one of the two internal alarms is triggered (that's why this pin is also called "INT").

Wise Clock 4 has the INT/SQW pin connected to D2 through a jumper. Therefore, to be able to use this RTC signal, a jumper must connect the 2-header pins, as shown in the picture below (jumper is red, between processor and SD card socket).


















Since I don't seem to get things perfect from the first try, I forgot to add the mandatory 10k pull-up resistor (this is fixed in the next iteration of the board, shipping as of mid Dec 2011). Here is how you need to connect the pull-up resistor, as shown in the next photo. Solder one terminal of the resistor in the via (it fits the hole) and the other terminal to the 2-pin header.


















Once the hardware is ready, compile and upload this very simple sketch.

#include "WProgram.h"
#include "Wire.h"
#include "DS3231.h"


void rtc_interrupt()
{
  Serial.println(millis());
}


void setup()
{
  RTC.enableSQW();
  Serial.begin(57600);
  Serial.println("RTC square wave enabled");
  pinMode(2, INPUT);
  attachInterrupt(2, rtc_interrupt, RISING);
}


void loop()
{
}

The sketch (tested with Arduino IDE 22) enables the 1Hz square wave on the RTC and attaches an ISR ("interrupt service routine") that gets executed once every second. (You can see the output of the ISR function in the serial monitor.)

Notes:
  • The square wave is not enabled by default as DS3231 gets powered. To enable the square wave, bit 2 of the register 0x0E must be set to 0 (it is 1 by default).
  • The square wave frequency can be one of the 4 values: 1Hz, 1024Hz, 4096Hz and 9182Hz. This frequency is selected by setting 2 bits (3 and 4) in control register 0x0E (check page 13 of the datasheet).
  • The file DS3231.h (also required is DS3231.cpp) is the one included in the WiseClock3 library.

I see at least two applications where this square wave/interrupt line can be used:
  • RTC alarm waking up the clock from sleep mode;
  • chronometer.

2 comments:

  1. Florin,

    I published an updated version of Time.h with the 1 Hertz reference added and 1ms accuracy.

    J

    http://code.google.com/p/clockthree/downloads/detail?name=Time.zip&can=2&q=#makechanges

    ReplyDelete
  2. Thanks Justin, I will take a closer look.

    ReplyDelete