The value of the tmr0 variable is not incremented

I have a code. The value of the tmr0 variable is not incremented. I can't understand why.

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

volatile uint32_t tmr1 = 0;

ISR(TIMER1_COMPA_vect) {
   tmr1++;
}

int main(void) {
   // initialize timer 1
   TCCR1B |= (1 << WGM12); // CTC mode
   OCR1A = 4; // value to get a period of 1 µs
   TIMSK1 |= (1 << OCIE1A); // enable interrupt by coincidence
   sei(); // global interrupt enable
  
   while (1) {
     if (tmr1 >= 500) {
       tmr1 = 0;
       // Next is my code
     }
   }
   return 0;
}

There is no tmr0 variable - have you posted the right code?

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

volatile uint32_t tmr0 = 0;

ISR(TIMER0_COMPA_vect) {
   tmr0++;
}

int main(void) {
   // initialize timer 1
   TCCR0B |= (1 << WGM01); // CTC mode
   OCR0A = 4; // value to get a period of 1 µs
   TIMSK0 |= (1 << OCIE0A); // enable interrupt by coincidence
   sei(); // global interrupt enable
  
   while (1) {
     if (tmr0 >= 500) {
       tmr0 = 0;
       // Next is my code
     }
   }
   return 0;
}

This works as expected. The timer was not initialized correctly, because you skipped the Arduino core initialization.

The 16MHz AVR-based Arduinos can't process an interrupt every microsecond. To learn about programming AVR timers, see this excellent tutorial: https://gammon.com.au/timers


volatile byte tmr0 = 0;

ISR(TIMER0_COMPA_vect) {
  tmr0++;
}

void setup() {
  // initialize timer 1
  Serial.begin(115200);
  while (!Serial);

  OCR0A = 250;
  TIMSK0 |= (1 << OCIE0A); // enable compare interrupt
}
void loop() {
  if (tmr0 >= 250) {
    Serial.println(tmr0);
    tmr0 = 0;
  }
}

If you do end up using a multi-byte variable with interrupts, not only does it need to be declared volatile, access to it outside the interrupt service routine must be done with care.

Most ppl grab their own copy of such a variable, viz:

  noInterrupts();
  uint32_t myTmr0Copy = tmr0;
  interrupts();

and use that everywhere they need tmr0.

HTH

a7

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.