PwmOut

Use the PwmOut class to control the period and pulse width (duty cycle) of digital signal.

Tips:

API

Public Member Functions

 PwmOut (PinName pin)
void write (float value)
float read ()
void period (float seconds)
void period_ms (int ms)
void period_us (int us)
void pulsewidth (float seconds)
void pulsewidth_ms (int ms)
void pulsewidth_us (int us)
PwmOutoperator= (float value)
PwmOutoperator= (PwmOut &rhs)
 operator float ()

Hello World!

This code example uses the default period of 0.020s and ramps the duty cycle from 0% to 100% in increments of 10%.

 


#include "mbed.h"

PwmOut led(LED1);

int main() {
    // specify period first
    led.period(4.0f);      // 4 second period
    led.write(0.50f);      // 50% duty cycle, relative to period
    //led = 0.5f;          // shorthand for led.write()
    //led.pulsewidth(2);   // alternative to led.write, set duty cycle time in seconds
    while(1);
}

Details

The default period is 0.020s, and the default pulse width is 0.

The PwmOut class can express the pulse width in many ways to fit different use cases. You can express the period and pulse width directly in units of seconds, millisecond or microseconds. You can also express the pulse width as a percentage of the the period.

Code Examples

Example one

This code example sets the period in seconds and the duty cycle as a percentage of the period in floating point (range: 0.0f to 1.0f). The effect of this code snippet will be to blink LED2 over a four-second cycle, 50% on, for a pattern of two seconds on, two seconds off.

 


#include "mbed.h"

PwmOut led(LED2);

int main() {
    // specify period first, then everything else
    led.period(4.0f);  // 4 second period
    led.write(0.50f);  // 50% duty cycle
    while(1);          // led flashing
}

Example two

The following example does the same thing, but instead of specifying the duty cycle as a relative percentage of the period, it specifies it as an absolute value in seconds. In this case we have a four-second period and a two-second duty cycle, meaning the LED will be on for two seconds and off for two seconds.

 


#include "mbed.h"

PwmOut led(LED2);

int main() {
    // specify period first, then everything else
    led.period(4.0f);  // 4 second period
    led.pulsewidth(2); // 2 second pulse (on)
    while(1);          // led flashing
}


Example three

This code example is for an RC Servo. In RC Servos you set the position based on the PWM signal’s pulse width or duty cycle. This example code uses a period of 0.020s and increases the pulse width by 0.0001s on each pass. This will cause an increase of 0.5% of the servo’s range every 0.25s. In effect the servo will move 2% of its range per second, meaning after 50 seconds the servo will have gone from 0% to 100% of its range.