PWMout frequency not changing

02 Feb 2011

I have written a simple PWM code which is reproduced below:

#include "mbed.h"

AnalogIn ain(p20);
PwmOut led(LED1);
PwmOut pin(p21);
int main() {
 
    while(1){
        
    float varf = ain.read();
    
    if(varf <= 0.1)
    {
      led = 0.1;
      pin = 0.1;
    }  
    else
    {
      led = varf;
      pin = varf;
    }  
    
    wait_ms(0.005);
    }

} //main

I am hoping that the wait_ms() as set above should give me a frequncy of 200KHz on pin 21. But no matter what I set this value I always get 50Hz. As I vary the voltage on pin 20 which is the analog in, the pulse width is varying correctly but not the frequency. I would appreciate if someone can shed some light on this. Thanks

02 Feb 2011

Hi Analog,

In your example, you are varying the dutycycle, which changes the pulsewidth (the percentage of time it is hight) for a given period.

I think you probably mean to be trying to set the period; take a look at the different options on:

Note that the period is shared among all PwmOut channels, so whilst the pulsewidth/dutycycle can be different on each channel, the period will be the same across them all.

Hope that helps,

Simon

04 Feb 2011

Thats right, if you want a frequency of 200KHz, you must change the period to 5us

pin.period_us(5)