ATmega328 Timer_2 Problem

I’ve tried to program timer 2 setting in my atmega 328 but there is a problem. I expect the word “Interrupt…” to be printed for every 1 second. Arduino Duemilanove runs at 16Mhz, ATmega 328 has 10 bit ADC and Timer 2 runs at 8 bit. To get the number of timer_2 overflows, I use this formula:

1 / ( 16000000 / (1024*256) ) = 1 / 61

so that means the arduino timer two has 61 overflows per second. However it is not the case. The word “Interrupt…” is printed out for every 2 seconds.

Below is my code

#include <avr/interrupt.h >
#include <avr/io.h >

#define INIT_TIMER_COUNT 0
#define RESET_TIMER2 TCNT2 = INIT_TIMER_COUNT

int int_counter = 0;

// Aruino runs at 16 Mhz, so we have 61 Overflows per second...
// 1/ ((16000000 / 1024) / 256) = 1 / 61
ISR(TIMER2_OVF_vect) 
{
  int_counter += 1;
  if (int_counter == 61) 
  {
    int_counter = 0;
    
    showData();
  }
};

void showData()
{
      Serial.print("Interrupt...");
}

void setup() {
  
  Serial.begin(9600);
  
  //Timer2 Settings:  Timer Prescaler /1024
  TCCR2B |= ((1 << CS22) | (1 << CS21) | (1 << CS20));
  
  //Timer2 Overflow Interrupt Enable
  TIMSK2 |= (1 << TOIE2);
  
  RESET_TIMER2;
  
  sei();
}

Any suggestion and help will be kindly appreciated. Thanks! :slight_smile:

Perhaps it only prints every other second because it takes a while to print, and you are missing an interrupt because you are bust printing, and interrupts are disable in the interrupt service routine.

Serial.print in an ISR is not recommended. Simply set a flag that indicates that something needs to be printed, and then, in loop, see if the flag is set, and, if it is, do the printing.