Teensy 4.0 4Mhz Clock Output

Lemoncheese

New member
I'm using a 4.0 with the audio shield and also want to drive a drive a chip which needs a 4MHz clock.

Ideally i'd like this 4MHz clock to be variable via a pot, or other analog input.

Is this possible ? What should I be looking into ?

Any help much appreciated.. Thanks..
 
Yes, you can get 4 MHz from the PWM pins, with code like this:

Code:
void setup() {
  analogWriteFrequency(2, 4000000);
  analogWrite(2, 128);
}

void loop() {
}

However, to get exactly 4 MHz you need to set Tools > CPU Speed to 528 MHz.

The PWM hardware divides a base clock, which is 1/4th of the CPU speed, by an integer. So with the CPU at 528, the PWM base is 132 MHz. But if you run at the default 600 MHz speed, the base is 150 MHz, so the nearest integers give 4.054 MHz and 3.947 MHz.

You can change the speed by calling analogWriteFrequency() and analogWrite() again. But there are 2 caveats. First is the integer divide, so you'll get discrete steps of appox 50 kHz. Second is this reconfigures the PWM, so you'll have a discontinuity (moment of ugly waveform) every time you change. Maybe that's ok if you change infrequently, but expect it to terrible if you change the setting rapidly.
 
Back
Top