9 years, 2 months ago.

PwmOut clears counter register when updating duty cycle?

I was experimenting with some LED dimming on a FRDM-KL25Z, and noticed that when the duty cycle is updated, the counter is cleared:

libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KLXX/pwmout_api.c: 84

void pwmout_write(pwmout_t* obj, float value) { ...

  • obj->CnV = (uint32_t)((float)(*obj->MOD + 1) * value);
  • obj->CNT = 0;

Clearing the counter seems to cause some glitching in the PWM output (presumably this will abort the current counter and restart it). I notice that the this causes some flickering. I commented out the line, and the LED dimming is much smoother. Looking at the user's manual, since the counters are in EPWM mode, the new limit is only loaded at the end of the duty cycle, so I am wondering if there is a good reason for clearing the counter.

Question relating to:

1 Answer

9 years, 2 months ago.

One possible reason is that the registers themselves are also only updated at the end of the cycle. So otherwise if you change the duty-cycle, and afterwards directly change the period, it will calculate the old duty-cycle with the too old compare value.

Although yeah in principle glitchless is nicer. FastPWM does all supported targets glitchless ;). (Except LPC11u24 changing period, but that can't be helped).

Accepted Answer

I can see that if you are changing both period & duty cycle, that could cause an issue, so perhaps resetting the counter when changing the period is a smart thing to do - changing the duty cycle seems to be a much more common operation (and one that you would want to be smooth if possible). I haven't tried FastPWM, since it wasn't part of the core libraries, but maybe worth trying. In any event, having removed the counter reset, the transitions are now very smooth (tried it out with 8 LEDs using offsets into an s-curve table, updating every 7 ms, no glitches). I am having lots of fun with this toy, and I am impressed with the mbed library support.

posted by Andrew McRae 01 Jan 2015