user2371490
user2371490

Reputation: 59

1 MHz timer on a 16 MHz ATmega8535

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.

It's quite simple:

My ATmega8535 runs at 16 MHz, and all I want is a timer of 1 MHz, so I can output some data on some pins at at 1 MHz basis.

So how do I proceed? The calculation below sounded OK (found here).

Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock Frequency) - 1
                   = (1 / 1000000) / (1 / 16000000) - 1
                   = 0.000001 / 0.0000000625 - 1
                   = 16 - 1
                   = 15

Then this would result in

void initTimer()
{
    // 8 bit timer 2 setup
    TCCR2 = (1<<CS20); // Timer clock = system clock/1
    TIFR  =  1<<TOV2;  // Clear TOV2/ clear pending interrupts
    TIMSK =  1<<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)
}

How can do these calculations correctly? Would this result in a 1 MHz timer?

Upvotes: 0

Views: 2144

Answers (1)

Arno Kalkman
Arno Kalkman

Reputation: 183

It is likely that the operation you are doing inside the interrupt function takes longer than the interval between interrupts. When you have a 1 MHz timer on a 16 MHz device you have 16 clock ticks between timer interrupts which is not a whole lot to do anything meaningful.

Besides, you also have the overhead of calling the interrupt function (this alone could be more than 16 ticks, but I don't know) which gives you less than 16 ticks to do something. When the code running inside your interrupt function takes more than the interval between interrupts you basically reduce your timer frequency by an unknown amount and leave very little CPU time for your main code.

I would suggest reducing the timer frequency so that your timer interrupt has enough time to run and enough CPU time is left for your main code (if you need that) or choosing a device that runs at a higher CPU frequency.

Upvotes: 2

Related Questions