Go Down

Topic: Generating 2 different frequencies only on timer 1 (Read 2213 times) previous topic - next topic


Is this possible.  I've looked thru the timer1 notes and I can't seem to be able to pull it off.

Can you generate two different frequencys only using timer1.

Any help appreciated.


I'd imagine it's one timer, one frequency.  For PWM, where there are six pins wired to three timers, that means two pins must share the same PWM frequency (but different PWM duty amounts).


Thanks.  I think your right.  I thought I might be able to use the 2 compare registers to generate different frequencies but what you've said makes perfect sense.


You can generate two different (or even three or four) frequencies from one timer. But it depends on what you really want to do. For instance, if you wanted a 10hz and 100hz frequency out of one timer you could set the timer to 100hz and also have it do something every 10 cycles. This can be expanded to as many freqs as you want. Obviously there are practical limits. Also, some freqs will be hard to combine. What if you need 1800hz and 11,000hz? You'd need to find the least common multiple. In this case you'd need a 99,000hz timer.


I havent messed with the compare registers on the AVR, but I have on the TI MSP430.  So- looking at the datasheet I think it works the same way.   You can get two different frequencies if you can handle the interrupts fast enough.  The neat thing is that you can get any increment of the timer frequency.

If you put two fixed values in the output compare registers, they will just interrupt at a fixed offset of a the timer period.  The trick is to put an updated value in the compare register every time it fires.

Set the timer to run continuously and just let it overflow.  Set your first two delays in your two compare registers.

When the first compare happens, your interrupt routine needs to add your interval to the compare value and update the compare register.  Likewise when the second compare matches, add its (longer or shorter) interval and update it.

The magic is that you just add a 16 bit value to your old compare value and IGNORE THE OVERFLOW.  Your math will overflow (wrap around) exactly like the timer.    Also, you have a fairly long time to update the registers because you just have to have the new value stuffed before the timer gets there.

That said - you need a fast interrupt handler, and you need to determine which compare triggered the interrupt.  You can do this in C, but you will probably have to set the hardware registers directly.  Also your maximum frequency is limited by the number of instructions in your interrupt handler.   I was doing servos, so there was always plenty of time.

This project doesnt do two frequencies, but it does mess with the same registers....

Go Up