Mistake on this page?
Report an issue in GitHub or email us


Use the PwmOut interface to control the frequency and duty cycle of a PWM signal.


  • Set the cycle time first, and then set the duty cycle using either a relative time period via the write() function or an absolute time period using the pulsewidth() function.
  • The default period is 0.020s, and the default pulse width is 0.

PwmOut class reference

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 ()
Protected Member Functions
void lock_deep_sleep ()
void unlock_deep_sleep ()
Protected Attributes
pwmout_t _pwm
bool _deep_sleep_locked

PwmOut 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

PwmOut 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 to 1). 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

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.