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?
If your module has DS3231M chip then according to datasheed this modification can only generate 1Hz signal on INT/SQW pin (3) and 32768Hz on 32kHz pin(1). I have several DS3231M's and checked it.
If your module has DS3231SN chip: I had a similar issue recently. Got 10 pcs of DS3231SN from ali. Soldered one IC to my board and discovered this problem. Luckily I had ZIF SO16 to DIP adapter and built a test-board, connected it to oscilloscope and tested all of them. Only 4 pcs of 10 was able to generate different signals (1024Hz, 4096Hz etc.) on SQW pin according to datashet. Also they generated stable 32768 Hz signal on 32KHz pin (pin 1).
Other 6(also marked as DS3231SN) gave only 1 Hz signal on SQW pin, all of them produced signal on 32 kHz pin (one IC generated about 35 kHz), one IC generated floating frequency signal on SQW pin (around 1500 Hz and it cant be changed). I think it's low quality fake IC's.