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?

1
  • 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);}. Commented Feb 24, 2017 at 16:30

1 Answer 1

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.

1
  • 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 Commented Feb 25, 2017 at 5:14

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.