4 years, 1 month ago.


Hi all,

I have a question regarding PWM output.

I want to set one of the pins on mbed to be PWM out, say (p21). After that I want to control the time PWM is sending pulses. I want to keep it switching on and off. For example:

PWM transmitting for 2ms, then it stops for 2ms. and it repeats again.

Any help would be great! Thanks.

Regards, Ben

Already found a solution, thanks!

posted by Saulius Janusauskas 18 Dec 2017

1 Answer

4 years, 1 month ago.

PWM is not designed for that use so it'll be hard to get it perfect. How exact does that 2ms have to be? If you change the PWM rate does it need to change immediately or is it ok if it only changes the next time the output turns on?

You could use a timer to turn the PWM on and off, something along the lines of:

float desiredPWM=0.5;
Ticker pwmOnOff;

void onTick() {
  static bool outputOn = true;
  if (outputOn)
    PWMpin =  desiredPWM;
    PWMpin =  0;
  outputOn = !outputOn;

main () {
    desiredPWM = setMyPWMValue();

It's not perfect but depending on the situation it may do.