A confusion with setting timers I was reading a tutorial on timers. My aim is to generate 16MHz pulse output from the pin 8.

Here is the code I modified from the tutorial (I use Arduino's ATmega328P):

#include &lt;avr/io.h&gt;
#include &lt;stdint.h&gt;


int main (void)
{
    DDRB |= (1 &lt;&lt; 0); // Set LED as output
    TCCR1B &amp;= ~(1 &lt;&lt; CS11); // Set up timer
    TCCR1B &amp;= ~(1 &lt;&lt; CS12); // Set up timer
    TCCR1B |= (1 &lt;&lt; CS10); // Set up timer


    for (;;)
    {
        // Check timer value in if statement
        if (TCNT1 &gt;= 0)
        {
            PORTB ^= (1 &lt;&lt; 0); // Toggle the LED
            TCNT1 = 0; // Reset timer value
        }
    }
}


I use the following formula:


  Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock
  Frequency) - 1


So Target Timer Count = 0 in my case.

But I get 615kHz on scope.

My timer setting should output 16MHz since I use no prescaler:



What am I doing wrong?
If you want to output a signal at the same speed as the system clock, I would not recommend using a timer.  You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.

The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.

If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top.  You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.