title: 1 MHz timer on a 16 MHz ATmega8535
body: <p>I can't seem to get my head around this, although it looks quite easy to me.
  I've made many timers in my Atmel ATmega8535, but this one just hits me.
  Also, I've seen many calculations and such, but it was not quite what I was looking for.</p>
  
  <p>It's quite simple:</p>
  
  <p>My ATmega8535 runs at 16 MHz, and all I want is a timer of 1&nbsp;MHz, so I can output some data on some pins at at 1&nbsp;MHz basis.</p>
  
  <p>So how do I proceed?
  The calculation below sounded OK (found <a href="http://tom-itx.dyndns.org:81/~webpage/abcminiuser/articles/avr_timers_index.php" rel="nofollow noreferrer">here</a>).</p>
  
  <pre><code>Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock Frequency) - 1
                     = (1 / 1000000) / (1 / 16000000) - 1
                     = 0.000001 / 0.0000000625 - 1
                     = 16 - 1
                     = 15
  </code></pre>
  
  <p>Then this would result in</p>
  
  <pre><code>void initTimer()
  {
      // 8 bit timer 2 setup
      TCCR2 = (1&lt;&lt;CS20); // Timer clock = system clock/1
      TIFR  =  1&lt;&lt;TOV2;  // Clear TOV2/ clear pending interrupts
      TIMSK =  1&lt;&lt;TOIE2; // Enable timer 2 overflow interrupt
      sei();
  }
  
  ISR(TIMER2_OVF_vect) // 16 bit timer 2 overflow interrupt vector
  {
      TCNT2 = 256-15;   // Make sure every overflow resets the TCNT2 to the 1 MHz setup
      addUpSomething++; // Do something (...not relevant to this sample)
  }
  </code></pre>
  
  <p>How can do these calculations correctly? Would this result in a 1 MHz timer?</p>