energia/Energia — pull request #372 by spirilis (2014-04-21 18:17:49+00:00)
Title: Repeated analogWrite() glitches occasionally

Reporting from 43oh- http://forum.43oh.com/topic/5361-odd-glitch-using-analogwrite-with-leds/

The user is rapidly changing the analogWrite() duty cycle of an LED pin to provide a smooth transition, and is noticing glitching in the LED output.

From what I can gather, I believe this is an artifact of the way analogWrite() works; every time it runs, it deconfigures the PWM pin back to OUTPUT and then re-configures its PxSEL bits, along with reconfiguring its timer pins; this could also cause glitching on other pins sharing the same timer peripheral, in theory.

analogWrite() should optimally know or store a flag as to whether each pin has been configured already for PWM operation, and perform an optimized duty cycle change if so. Any other functions such as pinMode, digitalWrite, etc should be aware of this and deconfigure the PWM state gracefully.