Is it possible to change the PWM frequency for the analog output pins on a Teensy4?

Status
Not open for further replies.
I am planning to make a 3 phase motor driver on a Teensy4. I measured the PWM frequency with a scope. It was about 7kHz. Normally in motor drivers use upwards 10kHz. The Teensy4 will be in the motor cotrol loop, so fast response is desirable at every point in the circuit.
 
The timers run from F_BUS which is 150 MHz, so at 10 MHz you should get only 16 levels (counting all low and all high).
 
Yup, use 585937.5.

analogWriteFrequency takes a float input for the frequency, so you can specify exactly the frequency you want, not limited by integer round off.
 
I have a loop to ramp the pulse width from 0% to 100% at 12 bit resolution. Is it possible to avoid the divide by 16 within the loop to save processor time. I tried to increment the loop by a fixed constant of 1/16 0.625 but it appears that I can only use integers for this. I know the Teensy4 can handle this amount of division easily at this stage, but I am just trying to get into good habits for later projects.

Code:
int v = 0;

void setup()   {                
    analogWriteFrequency(12, 36621.09375);
  pinMode(12, OUTPUT);
}

void loop()                     
{
 {
  for (int v = 0; v <= 4095; v=v+1) {
    analogWrite(12,v/16);
    delay(1);
  }
} 
}
 
There's a saying about premature optimization...

But to answer your question, if you really want to avoid integer division, why not just edit your loop and delay to use the numbers you want?

If you use an unsigned integer, the compiler can usually automatically replace division by powers of 2 by bit shift. Or if you really want to do that yourself, you could write "v >> 4".
 
Ahh, 0-255 is only for 8 bit resolution. I see it's possible to change the number of bits for this from 1-32 by using analogWriteResolution()
 
Status
Not open for further replies.
Back
Top