0
\$\begingroup\$

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 ?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$
7
  • \$\begingroup\$ Is it correct that by setting two interrupts with same vector in different timers that they do not work ? \$\endgroup\$
    – flowian
    Commented Oct 5, 2017 at 7:04
  • \$\begingroup\$ The ISR does not care what generates the interrupt; once it is generated then the ISR will be unconditionally executed. \$\endgroup\$ Commented Oct 5, 2017 at 7:06
  • \$\begingroup\$ So it is one ISR for all interrupts ? \$\endgroup\$
    – flowian
    Commented Oct 5, 2017 at 7:07
  • \$\begingroup\$ You can configure as many ISRs as you like. \$\endgroup\$ Commented Oct 5, 2017 at 7:08
  • \$\begingroup\$ Is it possible to use them separately though, without reading TIFRn bits. Maybe by setting #_COMPB_vect instead of #_COMPA_vect, just to have two different timers running at the same time. \$\endgroup\$
    – flowian
    Commented Oct 5, 2017 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.