NOTE: This is an archive of my old blog. Go to http://gonium.net for my current website.

Arduino Timer Interrupt

Posted by md on December 23, 2006

Continuing my interrupt experiments, I wrote a little sketch to print the seconds since startup to serial. But: Something is wrong…

I use the Timer2 of the ATMega8. It consists of a 8 bit counter which is automatically increased. When an overflow occurs, the interrupt routine TIMER2_OVF_vect is called.

This is the code:


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

#define INIT_TIMER_COUNT 0
#define RESET_TIMER2 TCNT2 = INIT_TIMER_COUNT

int ledPin = 13;
int int_counter = 0;
volatile int second = 0;
int oldSecond = 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) {
    second+=1;
    int_counter = 0;
  }
};

void setup() {
  Serial.begin(9600);
  Serial.println("Initializing timerinterrupt");
  //Timer2 Settings:  Timer Prescaler /1024
  TCCR2 |= ((1 < < CS22) | (1 << CS21) | (1 << CS20));
  //Timer2 Overflow Interrupt Enable
  TIMSK |= (1 << TOIE2);
  RESET_TIMER2;
  sei();
}

void loop() {
  if (oldSecond != second) {
    Serial.print(second);
    Serial.println(".");
    oldSecond = second;
  }
}

Unfortunately, the counter is not increased every second but every three seconds. I need to investigate this. Anyway, it seems to be more reasonable to use the CTC mode (clear-timer-on-compare-match). I need to read the datasheet ;-)

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments