I am trying to build a frequency meter using Interrupts and Timer1, which works as if the system receives an Interrupt it would get the timer's data and would calculate
Signal's Frequency = 1 / (Counter * Timer's Period) => F_s = F_t/TCNT
but the result is way off, and it does not even make sense. I have had altered my code to look that if the timer's data is not valid or sth, but the number that the timer counter has counted is sth that I expect.
Here is my code:
int f=0;
char msg[50];
void setup()
{
Serial.begin(115200);
noInterrupts(); // disable all interrupts
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
TCCR1A = 0;
TCCR1B = 0;
OCR1A = 0;
OCR1B = 0;
TCCR1B |= (0<<CS12)|(1<<CS11)|(0<<CS10); // Clock 2MHZ
TCNT1 = 0;
TIMSK1 = 0; // disable timer overflow interrupt
interrupts();
attachInterrupt(1,pin_ISR,RISING);
}
void pin_ISR(){
//digitalWrite(13,!digitalRead(13));
f = 2000000/TCNT1;
TCNT1=0;
}
void loop()
{
sprintf(msg,"Humidity:%d \n",f);
Serial.print(msg);
}
f
volatile and read it with interrupts blocked.