11 years, 1 month ago.

Incorrect PWM frequency below 12HZ.

I am programming three different PWM frequecies with duty cycle of 50%. The first two provides the correct output but the last one does not go to 1 HZ. Any ideas ?

  1. include "mbed.h"
  1. include "stdio.h"

PwmOut myled(LED1);

PwmOut IN1(PTD4);

float PWMtime_us; float pulsewidth;

int main() {

myled = 1;

while(1) {

PWMtime_us = (20000); pulsewidth = 0.5;

myled.period_us(PWMtime_us); myled.write(pulsewidth); Set Duty cycle IN1.period_us(PWMtime_us); IN1.write(pulsewidth);

wait (5);

PWMtime_us = (83333); pulsewidth = 0.5;

myled.period_us(PWMtime_us); myled.write(pulsewidth); IN1.period_us(PWMtime_us); IN1.write(pulsewidth);

wait (5);

PWMtime_us = (1000000); pulsewidth = 0.5;

myled.period_us(PWMtime_us); myled.write(pulsewidth); IN1.period_us(PWMtime_us); IN1.write(pulsewidth);

wait (5);

} End of While } End of Main

2 Answers

11 years, 1 month ago.

Use <<code>> and <</code>> around your code to make it readable. Also it is useful to inform us which platform you have (I assume the KL25).

The KL25 has a 16-bit PWM unit, with a prescaler between 1 and 128. In the mbed code it is hardcoded at 64, which allows for servo control for example. However 16-bit, 48MHz and 64 prescaler in less than 100ms as maximum period (so your 12Hz). The FastPWM library also changes the prescaler to allow for optimum control: http://mbed.org/users/Sissors/code/FastPWM/. However as said, the largest prescaler available to the KL25 is only two times larger, 128. So also the FastPWM library can't go lower than roughly 6Hz.

For example the 16-bit timers of the LPC11u24 also have a 16-bit prescaler, so they can make pretty much every period. Worse, the 32-bit timers on the LPCs also have 32-bit prescalers. And they have peripheral clock prescalers. So their maximum period is expressed in millennia. Which imo might be slightly on the overkill side of things. But yeah for the KL25 it is more limitted. To be fair, the vast majority of normal applications for PWM fall within its range, it is only you cannot led a LED blink slowly using PWM on it.

Thanks a bunch for your input, this explains everything.

posted by Asit Patel 01 Nov 2013
9 years, 9 months ago.

Actually, I am using an LCD that needs a 1Hz signal to refresh. I used a Ticker and a handler to flip the output, but my first idea was to use a PwmOut. Too bad it doesn't work below 20Hz.