title: AVR Interrupt Configuration
body: <p>The problem is that the timing behavior is totally wrong (factor 30).</p>
  
  <p>I have an ATmega 644PA which is running with 8 Mhz (CKDIV8 fuse is not set). <br/>
  I wanted an interrupt every 1 ms. I use Timer1 (16 bit timer) in the compare mode. <br/> 
  The prescaler was choiced by the timing range which i need. <br/> 
  Here 1 ms to ~2s. (limited through the 16 bit timer reg.)</p>
  
  <h2>Calculation</h2>
  
  <p>CPU: 8.000.000 Hz <br/>
  Prescaler: 256 <br/> <br/>
  8.000.000 Hz / 256 = 31250 Cycles / s (Hz)<br/></p>
  
  <p>1000 ms = 31250 Cycles <br/>
  1 ms = 30.25 Cycles (31.25 - 1, timer reg. start by 0)<br/></p>
  
  <p>From here i can calculate it up, for example:<br/>
  100 ms = 3025 Cycles <br/>
  2s = 60500 Cycles <br/></p>
  
  <h2>Code</h2>
  
  <p>Timer Init <br/></p>
  
  <pre><code>    cli();                  // disable global interrupts
      TCCR1A = (1 &lt;&lt; WGM01);  // CTC ON
      TCCR1B = 0x04;          // Prescaler 256
      OCR1A  = 30;            // set compare reg.
      TIMSK1 = (1 &lt;&lt; OCIE1A); // set interrupt mask
      TCNT1  = 0x00;          // set counter reg. to zero
      sei();                  // enable global interrupts
  </code></pre>
  
  <p>ISR: <br/></p>
  
  <pre><code>ISR(TIMER1_COMPA_vect)
  {
    // start own code
    ...
    // end own code
    TCNT1 = 0x00; // reset counter reg. to zero after match (same which should CTC do)
  }
  </code></pre>
  
  <p>Now i have for example a volatile variable which will be incremented in the ISR function. <br/>
  I'm polling the variable and wait so long till it reach 60500, which is equal to 2s. <br/> 
  After it i just set an led on.<br/></p>
  
  <p>I measured it by phone and it takes 1 minute till the led goes on. <br/>
  It takes to long with the factor 30 => 60s divided by 2s are 30.  <br/>
  I also tried to use an external program to calculate it, it came to the same results. (0x1E = 30) <br/>
  <a href="https://i.stack.imgur.com/tduN8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tduN8.png" alt="Screenshot"></a>
  </p>
  
  <p>Someone an idea where my mistake is ?</p>