Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

Thread: Teensy 4.0 4Mhz Clock Output

  1. #1
    Junior Member
    Join Date
    Jul 2020
    Posts
    2

    Teensy 4.0 4Mhz Clock Output

    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..

  2. #2
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    22,777
    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.

  3. #3
    Junior Member
    Join Date
    Jul 2020
    Posts
    2
    Thank you Paul, I knew there'd be a simple way to do it !

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •