NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » How to obtain a high frequency generator AND a high resolution with the timers?

June 27, 2010
by Frozenlock
Frozenlock's Avatar

Here is my problem: I've successfully obtained a a high frequency generator with one of the MCU's timers. However, the frequency follows this equation: F = Clock / (2 * N (1+ OCRnx)). This gives the following selectable frequencies (in kHz):

7,372.80

3,686.40

2,457.60

1,843.20

1,474.56

1,228.80

1,053.26

921.60

As you can see, there's a HUGE void between the selectable frequencies. (Around 50% for the firsts)

If I need a frequency of 1300 kHz, am I doomed?

Is there a way to use the interrupt, or perhaps a combination of timers to be able to obtain a larger selection of frequencies?

Thank you very much in advance!

June 28, 2010
by bretm
bretm's Avatar

You can obtain an exact average frequency. Some cycles will be slightly long, some slightly short, but they'll all be one or the other, and the average will be the desired frequency. The general scheme goes like this:

volatile long counter;

void MyInterruptRoutine()
{
    const long actualFrequency = 737280;
    const long desiredFrequency = 130000;

    counter += desiredFrequency;

    if (counter >= actualFrequency)
    {
        counter -= actualFrequency;
        DoStuffAtDesiredFrequency(); // to be written
    }
}

void main()
{
    counter = 0;
    initializeInterrupt(); // to be written
}
June 28, 2010
by Frozenlock
Frozenlock's Avatar

I don't know yet if an average frequency will do the trick, but I'll try.

Thanks!

June 29, 2010
by bretm
bretm's Avatar

Note: Those specific values wouldn't work because 7.3728MHz is too fast for an interrupt routine on an Atmega, because it wouldn't leave enough clock cycles to do the interrupt processing.

Another change, to help performance, is to reduce whatever your fraction is (737280/130000 in this case) to it's simplest equivalent form (9216/1625 in this case). This makes it harder to tell what's going on (so add comments), but allows you to use int instead of long which will save a lot of clock cycles.

Post a Reply

Please log in to post a reply.

Did you know that you can generate hundreds of volts AC from your microcontroller with a little bit of circuitry? Learn more...