title: how to activate 16bit timer on AVR programming
body: <p>I have an atmega168a chip. I use <code>Counter 0</code> to toggle <code>PORTC</code> by using <code>ISR(TIMER0_COMPA_vect)</code> and <code>ISR(TIMERB_COMPA_vect)</code> interrupt sub-routines. I would like to activate the <code>16-bit timer</code> when <code>if</code> condition is true. So, I use <code>TIMSK1 = (1&lt;&lt;OCIE1A)</code>, but this line calls <code>ISR(TIMER1_COMPA_vect)</code> interrupt instantly where I want 16 bit timer to be interrupted only when the counter <code>reaches</code> to <code>OCR1A</code> value. How can I activate the 16-bit timer on the run-time without causing an instant interrupt?</p>
  
  <p>here is my code:</p>
  
  <pre><code>#define F_CPU 8000000
  #include &lt;avr/io.h&gt;
  #include &lt;avr/interrupt.h&gt;
  #include &lt;stdint.h&gt;
  
  volatile uint8_t counter;
  
  int main (void){
      DDRC = 0xFF;  //sets PORTC as output
      PORTC = 0xFF; //initial output value
      /*COUNTER0 settings*/
      TIMSK0 = ((1&lt;&lt;OCIE0A) | (1&lt;&lt;OCIE0B));  // Enable Interrupt TimerCounter0 Compare Match A &amp; B
      TCCR0A = (1&lt;&lt;WGM01);  // Mode = CTC
      TCCR0B = (1&lt;&lt;CS01) | (1&lt;&lt;CS00);   // Clock/64, 1/(8000000/64)= 0.000008 seconds per tick
      OCR0A = 200;      //   0.000008 *230 = 1.6 ms
      OCR0B = 100;      //     0.8 ms
  
      /*16bit timer - counter1 settings*/
      TIMSK1 &amp;= ~(1&lt;&lt;OCIE1A); // Disable Interrupt Counter 1, output compare A (TIMER1_CMPA_vect)
      TCCR1B = ((1&lt;&lt;CS12) | (1&lt;&lt;CS10) | (1&lt;&lt;WGM12));    // Clock/1024, 1/(8000000/1024) = 0.000128 seconds per tick, Mode=CTC
      OCR1A = 40;                       // 0.000128*40 ~= 5.12 milliseconds
  
      sei(); //interrupts are globally switched on
      counter =0;
      while(1){
          if(counter &gt;= 4){
              TCNT1 = 0; // clear the counter 1
              TIMSK1 = (1&lt;&lt;OCIE1A);// Enables the interrupt for Counter 1,(TIMER1_CMPA_vect)
              TIMSK0 &amp;= ~((1&lt;&lt;OCIE0A) | (1&lt;&lt;OCIE0B)); //disables the Counter 0's interrupts
              counter = 0;
          }
      }
      return 0;
  }
  
  ISR(TIMER0_COMPA_vect){ //1.6ms
      PORTC = 0xFF;
      counter++;
  }
  
  ISR(TIMER0_COMPB_vect){  //0.8 ms
      PORTC = ~PORTC;
  }
  
  ISR(TIMER1_COMPA_vect){ // 5.2 milisecond interrupt
      PORTC = 0x00;
      TCNT0 = 0; //clear the counter of counter0
  //  TIMSK0 = ((1&lt;&lt;OCIE0A) | (1&lt;&lt;OCIE0B)); //Enable the Counter 0 interrupts
  //  TIMSK1 &amp;= ~(1&lt;&lt;OCIE1A);// Disable Interrupt Counter 1, output compare A (TIMER1_CMPA_vect)
  }
  </code></pre>
  
  <p>here is an oscilloscope output that shows why I don't want the interrupt to be set instantly, because it set the signal 0 instantly.
  <img src="https://i.stack.imgur.com/FW7Mi.png" alt="enter image description here"></p>