I am using an Arduino Mega2560 to count an unknown frequency. For that, timer5 is operating in input capture mode with an RTC DS3231's SQW pin generating an interrupt on arduino pin 48 (ICP5) after 1s.
The unknown frequency is input into pin 47 (T5 pin).
The code was working fine when I tested it with input from a function generator. There was no error in measurement upto 100kHz.
Today, I uploaded the same code to the board, and at an input frequency of 1kHz, the count displayed was 2 Hz.
The code I'm using is as follows:
#include <RTClib.h>
#include <Wire.h>
RTC_DS3231 rtc;
volatile int long t5val;
volatile bool counterReady = false;
volatile int long ovfcount;
volatile int long OVF;
ISR(TIMER5_OVF_vect) {
ovfcount++;
}
ISR(TIMER5_CAPT_vect) {
TIMSK5 = 0;
t5val = TCNT5;
OVF = ovfcount;
TIMSK5 = bit(TOIE5) | bit(ICIE5);
counterReady = true;
TCNT5 = 0;
ovfcount = 0;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
rtc.writeSqwPinMode(DS3231_SquareWave1Hz);
//timer setup
TCCR5A = 0;
TCCR5B = 0;
TCCR5B = bit(CS52) | bit(CS51) | bit(CS50);
TIMSK5 = bit(ICIE5) | bit(TOIE5);
TCNT5 = 0;
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
while (1) delay(10);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, let's set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
if (counterReady) { t5val += OVF * 65536; }
Serial.println(t5val);
DateTime now = rtc.now();
delay(1000);
}
I tried debugging by rewriting parts of the program separately, ie, just to test if timer 5 is working in counter mode, output compare mode, if it is overflowing correctly at sufficient input, if it is receiving 1hz signal from RTC.
Individually, these components are working. But the program attached above doesn't work, even though the exact same program worked flawlessly a week ago.
I even hooked up the function generator to an oscilloscope to confirm there was no error in its output (there wasn't).