1

I have set up a very simple test program to blink an builtin LED using PWM. Following the mbed example and setting the period to 4 seconds (0.25 Hz) and duty cycle to 0.5, the expected behaviour is for the LED to be on for 2 seconds and off for 2 seconds. However, the actual behaviour is that the LED flashes extremely quickly (almost imperceptable to the eye).

#include "mbed.h"

mbed::PwmOut ledPin = mbed::PwmOut(P0_13); //builtin led pin

void setup() {
  ledPin.period(4.0f);
  ledPin.write(0.0f);
}


void loop() {
  // put your main code here, to run repeatedly:
  ledPin.write(0.5f);
}

I have tried adding delay() and wait_ns() with different times in the main loop, tried having the main loop empty and setting the duty cycle in the setup() function as well as changing the period to larger numbers just in case it was in milliseconds all to no avail. Not quite sure what I'm missing from this extremely simple example.

1
  • According to mbed example, to create an instance of PwmOut object, it should be PwmOut ledPin(P0_13). For the setup(), set the duty cycle to 50% with ledPin.write(0.5f);, and delete the code within the loop() as itself is already a while(1) loop.
    – hcheung
    Jul 16, 2023 at 3:27

1 Answer 1

0

The example you linked has an infinite, but empty, loop - while(1); - following setting up the PWM.

Your loop repeatedly executes ledpin.out(0.5f);

I didn't find the .out() member function to know what it does but my first thought would be comment out the contents of your loop() function and let it also run as an empty infinite loop. Then I'd look at the .out member function and find out what its action is. Output to a pin is usually a boolean. If that is the case with .out(), then 0.5f will be converted to an integer 0 which is identical to boolean 'false', and this loop would repeatedly turn off the LED, and at around a megahertz.

1
  • The code he posted executes ledPin.write(0.5f); inside loop, not out.
    – Nick Gammon
    Jul 16, 2023 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.