OPTIMIZING CODE FOR PWM efficiency

For some projects, it’s alright to have a microcontroller twiddling it’s thumbs many of the time. When a project requires the cpu to do just one thing over and over, there’s no loss with inefficient code – it either works or it doesn’t. However, if a project requires a microcontroller to do several things at once, like reading sensors, dimming LEDs, and writing serial data out, cpu utilization can become an issue. [Robert] wasn’t pleased with the code he used to control a string of LEDs, so he rewrote his code. With the old implementation, [Robert]’s code used 60% of the cpu time. With the new and improved code, the cpu was only busy 8% of the time.

The code works by using a hardware timer to set off an interrupt. After calculating the next time it ought to run again, and changing the state of the data line, the code just sits quietly until it’s needed again.

It’s not a pretty hack, or even one you can hold in your hands, but [Robert]’s determination in getting a μC to do what he wants is admirable.

Leave a Reply

Your email address will not be published. Required fields are marked *