1

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 <avr/io.h>
#include <stdint.h>


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


    for (;;)
    {
        // Check timer value in if statement
        if (TCNT1 >= 0)
        {
            PORTB ^= (1 << 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:

enter image description here

What am I doing wrong?

  • You can have the timer toggle the led, instead of doing it yourself (by using the COM1A1/COM1B1 bits in the TCCR1A register. To set the maximum value of the timer from 65535, set the timer to CTC mode, and set OCR1A to 1 (or maybe 0). If you want to do software PWM, just use while(true){PORTB ^= (1 << 0);}. – Gerben Feb 24 '17 at 16:30
4

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.

  • I agree with this. This is the only way that the Atmega328P running at 16 MHz can output a 16 MHz signal. Using timers the maximum you can get is 8 MHz. If you want to see code that does 8 MHz using timers see Example of generating 8 MHz signal – Nick Gammon Feb 25 '17 at 5:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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