How often does timer/counter interrupt execute

Thread Starter

Sonoma_Dog

Joined Jul 24, 2008
99
all right, so i have successfully done my first interrupt programming. but i am still not sure how often does the program go into the interrupt. Since i dont have an oscilloscope to verify the timing. so my guesses is all based on calculations.

I am using a 8bit timer/counter, 16Mhz crystals and the interrupt setting is overflowing with 1024 prescaler.

in the datasheet, i found this equation: f_ocnx=f_clock_IO/(2*N*(1+OCRnx))

so i guess my OCRnx is 256, wince i am using a 8 bit counter. And if i am not wrong. my N will be 1024 and f_clock_IO is 16Mhz

So does it means the interrupt will execute at [f_ocnx= 16Mhz/(2*1024*(1+255))] 30.51Hz, which also mean every 32.7ms.

is my calulation correct? and also, can anyone tell me why is there a 2 in the denominator?

Thanks
 

atferrari

Joined Jan 6, 2004
5,016
Want you know if you are in the ballpark?

If you have a scope available:

In the interrupt service routine, set one output pin immediately after the overhead dedicated to save the environment, and immediately BEFORE retrieving the environment, reset it.

For the different settings you could see how close you are. In all my designs I keep this to know that the ISR is active. Saved a lot of guesswork.
 

AlexR

Joined Jan 16, 2008
732
What chip family are you using?
Where is clock sourced from, CPU clock or a separate timer clock?
Without this basic info there is no way to check your calculations.
 

Thread Starter

Sonoma_Dog

Joined Jul 24, 2008
99
No, i do not have an scope with me at home, that would make it so much easier. :(


What chip family are you using?
Where is clock sourced from, CPU clock or a separate timer clock?
Without this basic info there is no way to check your calculations.

I am using a ATmage168 chip and i believe i will be using a external clock sources, a crystal 16mhz oscillator.

thanks!
 

nanovate

Joined May 7, 2007
666
create a variable to be used inside the timer interrupt
connect a LED to a pin
toggle the pin when the variable reaches a certain value


Here is an example using Timer 1 (16 bit) on the ATmega168 with the gcc compiler.
This will toggle the pin on Port B every second based on a 16MHz clock.
Rich (BB code):
#include <avr/io.h> 
#include <avr/interrupt.h> 

volatile unsigned int blink;

int main (void) 
{ 
   DDRB |= (1 << 0); // Set LED as output 

   TCCR1B |= (1 << WGM12); //Set up Timer 1 for CTC mode 

   TIMSK1 |= (1 << OCIE1A); // Enable the CTC interrupt 

   sei(); //  Enable global interrupts 

   OCR1A   = 15625; // Set CTC compare value 

   TCCR1B |= ((1 << CS10) | (1 << CS11)); // Start timer at Fcpu/64 (250 kHz)

   while(1);
   
} 

ISR(TIMER1_COMPA_vect) 
{ 
   
   blink++;
   if(blink > 15)
  {
       PORTB ^= (1 << 0); // Toggle the LED on PORTB
       blink = 0;
  }  

}
 
Top