Need help generating a fast (~1.5Mhz) output clock from a timer

Howdy,

I want to generate a fast clock using a timer on my UNO board, but I need some help configuring things for it to work.

Initially I'm guessing that I want to run a timer in non-PWM mode in toggle on compare in a way that will allow just a few unscaled ticks and then toggle an output.

Can this be configured to output a ~1.5Mhz square wave without requiring an ISR to flip a port pin?

If someone could tell me how to configure a timer or point me to an example which implements what I'm asking I'd be very grateful.

You should be able to do it with no prescaler and counting up to 24.

I don't understand Nick's answer. I was going to say count to 4 for 1.60MHz or 5 for 1.33MHz. What am I missing?

Er, I miscalculated there. You won’t get it exact, because 1.5 MHz would be a period of 0.0000006666 seconds (666 nS) and the clock period (62.5 nS) doesn’t divide into that evenly.

666 / 62.5 = 10.656

So, counting up to 9 (because it is zero-relative) using fast PWM gives reasonable results:

#include <TimerHelpers.h>
void setup() {
   pinMode (3, OUTPUT); 
   OCR2A = 9;
   OCR2B = 4;
   Timer2::setMode (7, Timer2::PRESCALE_1, Timer2::CLEAR_B_ON_COMPARE);
}  // end of setup
void loop() {}

I measured 1.6 MHz on pin 3.

If you increase the count from 9 to 10 (so really, counting to 11) you get 1.45 MHz.

I don't understand Nick's answer. I was going to say count to 4 for 1.60MHz or 5 for 1.33MHz. What am I missing?

I was wrong. :wink:

Oh, I see. You can do this in mode 7 to get a slightly asymmetric "square" wave, but with an overall frequency that is closer to 1.5MHz than what I was thinking of.

My code above without the library:

void setup() 
  {
   pinMode (3, OUTPUT); 
   OCR2A = 9;   // count to 10  (zero-relative)
   OCR2B = 4;   // count to 5
   TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1);  // Fast PWM, clear OCRB on compare
   TCCR2B = bit (WGM22) | bit (CS20);   // Fast PWM (mode 7), prescaler of 1
  }  // end of setup
void loop() {}

Thanks so much you guys. Great help.

I edited the above posts (which is bad of me). I adjusted the counters to be 9 and 4 which is really 10 and 5 allowing for the zero-relative part, which now gives a symmetric square wave.

jboyton:
Oh, I see. You can do this in mode 7 to get a slightly asymmetric “square” wave, but with an overall frequency that is closer to 1.5MHz than what I was thinking of.

Yes, the fast PWM gives a faster frequency (and hence finer control) but is not phase-correct (which won’t matter in this case).

jboyton:
I don't understand Nick's answer. I was going to say count to 4 for 1.60MHz or 5 for 1.33MHz. What am I missing?

I was thinking that at 16 MHz you count to 16 for 1 MHz, and therefore for 1.5 MHz you multiply 16 by 1.5 giving 24. However that gave a period of 1.5 µS not a frequency of 1.5 MHz.