I want to use a DS3231 RTC (ZS-042) to make precise time measurements on my arduino uno. I need to measure milliseconds, to the regular time functions of the various RTC libs are not enought.
After googling & asking aroung I found that I need to use the SQW output of the DS3231 and attach it to an interrupt or timer. When using the appropriate rate, I would be able to perform time measurements.
So I tried wiring the SQW to pin 5 on my arduino uno (which is the T1 input), and configure T1 to use an external source. I used some RTC lib to enable the SQW output and set it to 1024hz. Then I attached the ISR for counting ticks and overflows.
All this seems to basically work, however the SQW signal seems to be stuck at 1hz, no matter what I do.
Here is my code:
#include <Wire.h> //I2C library
#include <RtcDS3231.h> //RTC library
RtcDS3231 <TwoWire> rtcObject(Wire);
static volatile unsigned long overflows = 0;
void setup() {
Serial.begin(9600);
rtcObject.Begin(); //Starts I2C
rtcObject.SetSquareWavePin(DS3231SquareWavePin_ModeClock); //Sets pin mode
rtcObject.SetSquareWavePinClockFrequency(DS3231SquareWaveClock_1kHz); //Sets frequency
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 32000;
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS11); // external source / no prescaler
TCCR1B |= (1 << CS12); // external source / no prescaler
// TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
interrupts(); // enable all interrupts
}
ISR(TIMER1_OVF_vect)
{
TCNT1 = 0;
overflows++;
}
void loop() {
delay(1024);
Serial.println("loop");
Serial.println(TCNT1);
}
which will print something like:
loop
1
loop
2
loop
3
What is wrong/missing in my code?