Electrical – How to use two timers for one interrupt vector on avr

atmega328pinterruptstimer

I want to use timer1 and timer2 for same vector TIMER#_COMPA_vect isr on atmega328p.
Idea is to start and stop one when requested, for time sensitive functions. And to keep another running always for clock time keeping.

When initializing both timers, they don't work. Whereas they do when initializing separately.

Timer2

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 = 15;

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

Timer1

void timer1CtcInit(void){
//timer1 for 100 ms
  cli();
  TCCR1B = 0;
  TCCR1A = 0;


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

  sei();

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

Followed by two ISRs

ISR (TIMER1_COMPA_vect){
tmr1Count++;
}

and

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

All this does not work together.

Edit

I guess OP is somewhat misleading of my aim.
I want to use two timers for different time interrupts. One for keeping clock time on LCD and other for giving pulses at certain times. For some reason Timers don't work as expected when initializing both – Timer2 gets higher priority and Timer1 is not working.
Timers are tested on LCD display, Timer2 for seconds and Timer1 minutes.

How to set two timers running simultaneously ?

Best Answer

ISR_ALIASOF() in the ISR attributes will let you reuse one ISR for another interrupt.

ISR(TIMER2_COMPA_vect, ISR_ALIASOF(TIMER1_COMPA_vect));

You can tell which timer triggered the ISR by examining the appropriate OCFnx bits in TIFRn.