Electrical – How to set two timers running at the same time in atmega328p

atmega328pinterruptstimer

I want to set up two timers running two ISR-s with different resolutions.
One timer for counting milliseconds for clock time, another for counting microseconds when requested.
I've set up Timer1 and Timer2 in CTC mode, but timer with microseconds(Timer2) gets higher priority and timer with milliseconds is ignored(Timer1). Whereas they work separately well.

The setup:

void timer1CtcInit(void)
{

  TCCR1B = 0;
  TCCR1A = 0;


  //set CTC mode
  TCCR1B |= (1 << WGM12);
  // enable compare match interrupt
  TIMSK1 |= (1 << OCIE1A);


  // set OCR0A value for 100 msec
  OCR1A = 0x0619;
  //set 1024 prescaler
  TCCR1B |= (( 1 << CS10) | (1 << CS12));
}
void timer2CtcInit(void)
{

  //Timer 2 interrupt service routine CTC settings, 1 uS:
  TCCR2A = 0;
  TCCR2B = 0;
  //set CTC mode
  TCCR2A |= (1 << WGM21);
  //prescaler 1 for timer2
  TCCR2B |= (1 << CS20);

  // value for 1 usec
  OCR2A = 0x0f;

  //set compare match for register OCRA
  TIMSK2 |= (1 << OCIE2A);
}

ISRs:

ISR(TIMER2_COMPA_vect){
  if (timerFlag){
    tmr2Count++;
  }
}

ISR(TIMER1_COMPA_vect){
  tmr1Count++;
}

Best Answer

Thanks to @brhans for bringing awareness of prescalers.
I think what happened was that interrupt setup with no prescaler was being depleted by other functions which took many mcu cycles to complete. The conflict was resolved by setting microseconds timer to 20 us instead of 1 and setting prescaler to 32. For timer with milliseconds prescaler was set to 256.