Forum Rule: Always post complete source code & details to reproduce any issue!

# Thread: Need to confirm PWM math and syntax

1. ## Need to confirm PWM math and syntax

I need to generate two PWM frequencies around 40Khz separated by about 32hz on a Teensy4. According to the PWM page, it seems I should choose:
Resolution = 11 bits
Ideal frequency = 73242 hz
This gives a frequency resolution: 73242/2048=35.76hz
This is close enough to 32hz to work.
Is this the correct way to calculate what frequencies are available? ie 35.76hz * n

AnalogWriteFrequency does some rounding etc to get the closest frequency to what was input, so I need another way to set the frequency so I know the exact PWM frequency I’m going to get. Is there an easier way to do this other than direct register manipulation?

2. With analogWriteResolution set to 11 I can see the frequency resolution coming out to about 10.5hz. This is not what I expected per above, so there must be some other calculations I need to understand.

3. In cases like this, it might help if you posted your example sketch, so maybe one could try it and get an idea of what exactly you are calling and what is happening.

4. Without code it isn't clear if this was called for desired frequency :: analogWriteFrequency(uint8_t pin, float frequency);

For a given resolution a range of clock setting are available to specify the desired frequency. It will default to 'some' frequency - if another is desired and available it must be so indicated.

5. Below are the relevant code fragments. I'm working only with pins 23 and 22 presently. I arrived at the frequency settings by trial and error. The pwm frequency only changes in notches of about 10.5hz
I need to be able to match a corresponding receiver interrupt that is 4x the frequency of the one configured here. I'm presently using intervaltimer with a fudge factor I tweaked by trial and error, but would prefer to utilize the timers better.

Code:
```int US_Tx_PINs=4;
int US_Tx_PIN[]={23,22,14,15};
uint32_t US_Tx_Freq[]={40005,40037,39488,39456};

analogWriteResolution(11);
for(int i=0;i<US_Tx_PINs;i++){
pinMode(US_Tx_PIN[i],OUTPUT);
analogWriteFrequency(US_Tx_PIN[i],US_Tx_Freq[i]);
analogWrite(US_Tx_PIN[i],1024);
}```

6. Thanks details like your simple sketch shows me a lot of information.

pins 22 and 23 use FlexPWM timer 23(PWM module 4, sub-module 1 Pin A), 22 PWM module 4, Sub module 0 pin A)

Where as pins 14 and 15 use Quad Timers 14(Timer 3 pin 2), 15 Timer(3 pine 3)

Not to say they can not be configured to work, but just a heads up that you are working with a couple different timer types which may have different capabilities.

#### Posting Permissions

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