Timer 1 Running Unexpected speed?

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I was just following the tutorial https://www.avrfreaks.net/index.p...

on timers. I am using a ATMEGA2561 with a crystal clock @ 16 MHZ (fuse bits set to use external clock). I tried the first example in the tutorial, and using the formula:
(1/Desired Frequency)/(1/Clock Frequency) - 1

my desired frequency is 500 Hz, so count should be:
(1/500)/(1/16000000) - 1 = 31999;

So my code is:

#include "avr\io.h"

int main(void)
{
	DDRA |= (1 << 0); 	// Set port A0 as output


	TCCR1B |= (1 << CS10);	// Set up timer with prescaler 1 (no prescale)

	while(1)
	{
		if(TCNT1 >= 31999)
		{
			PORTA ^= (1 << 0); // Toggle port
			TCNT1 = 0;		//	Reset timer count
		}

	}
}

However, my oscilloscope shows I get 250 Hz. If you adjust my numbers in that formula from 500 --> 250 and 16000000 --> 8000000, it appears my system clock is running at half speed. I am not sure why this is happening.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

500Hz is a 2 millisecond period. 1 millisecond on; 1 millisecond off. So you need a toggle every millisecond (1000 transitions per second) not 500.

You can put lipstick on a pig, but it is still a pig.

I've never met a pig I didn't like, as long as you have some salt and pepper.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Gotcha because it's toggling on every pulse. Thanks!