PWM frequency library

runnerup:
I discovered in a recent project involving an Arduino microcontroller that there was no method to change PWM frequency without directly manipulating low-level memory. As far as I can Google, there is no general purpose library that can change PWM frequencies on Arduino Microcontrollers. The internet is full of partial examples and code snippets for changing PWM frequency, but in the end I still had to consult the 400+ page sec sheet (http://www.atmel.com/Images/doc2549.pdf) to get the code for my Mega functional.
It is my speculation that the programmers at Arduino have not released any methods for changing PWM frequency because it is difficult to write a simple and intuitive wrapper for hardware timers that wont run the risk of confusing a beginner (the whole draw to Arduino in the first place). The hardware is has very specific limitations that present themselves in odd ways. Allow me to share a few:

  • PWM behavior is determined by integrated components called timers. Every timer has two to four channels. Each channel is connected to a pin. Changing one pin's frequency requires changes to the timer it connects to. Which in turn changes the frequency of other pins connected to that same timer.
  • Timer 0 is usually used for Arduino's time keeping functions, (i.e. the millis() function). Changing the frequency on timer 0 will break the time keeping functions you may or may not be using in other parts of your project
  • There are two types of timer, 8bit and 16bit. Long story short, they have nuances that make common code difficult to implement without limiting one or the other.
  • Creating custom frequencies (beyond messing with the prescaler) with an 8bit timer requires the sacrifice of one channel. In other words, each 8bit timer that creates a custom frequency loses the ability to perform PWM on one pin (the one connected to the A channel to be more precise). All Arduinos except the Leonardo have two 8bit timers, meaning that setting all timers to a particular frequency will sacrifice a total of two pins on said Ardiuno.

Regardless of this, I still felt it would still be worth while to make a library/wrapper for hardware timers so that I, and anyone else who chooses to use this, will not have to spend quite as many hours needlessly digging through blocks of bug prone bit wise and preprocessor slurry.

The library has five global functions:

InitTimers() Initializes all timers. Needs to be called before changing the timers frequency or setting the duty on a pin
InitTimersSafe() Same as InitTimers() except timer 0 is not initialized in order to preserve time keeping functions
pwmWrite(uint8_t pin, uint8_t val) Same as 'analogWrite()', but it only works with initialized timers. Continue to use analogWrite() on uninitialized timers
SetPinFrequency(int8_t pin, int32_t frequency) Sets the pin's frequency (in Hz) and returns a bool for success
SetPinFrequencySafe(int8_t pin, int32_t frequency) Same as SetPinFrequency except it does not affect timer 0

The library also has five functions for each Timer 'object'. I could not get the code size down to what I felt was reasonable so I ditched C++ classes and did some fancy macro work instead. Each of these functions are technically preprocessor macros with nice self explanatory names that swap out for more cryptic functions inside the library header just before compile time. For timer 1 the functions are:

Timer1_GetFrequency() Gets the timer's frequency in Hz
Timer1_SetFrequency(int frequency) Sets the timer's frequency in Hz
Timer1_GetPrescaler() Gets the value (not bits) of the prescaler. Don't know what this means? Don't worry about it, just use SetFrequency(int frequency)
Timer1_SetPrescaler(enum value) Sets the prescaler*
Timer1_GetTop() Gets the timer register's maximum value
Timer1_SetTop(int top) Sets the timer register's maximum value
Timer1_Initialize() Initializes the timer

*The prescaler is inconsistent among different timers. I figured using enumerators was the best solution because most types of invalid input will be caught at compile time. For a normal timer, use one of these as a parameter: ps_1, ps_8, ps_64, ps_256, ps_1024. If those give a type error, then the timer you are using is one of the inconsistent ones, and you should use psalt_1, psalt_8, psalt_32, psalt_64, psalt_128, psalt_256, or psalt_1024 instead.

If you want to mess with a different timer, just change the number (i.e Timer2_GetFrequency() to get timer 2's frequency). It is up to your discretion whether or not you want to use the timer specific functions. The global ones should be good enough for most situations.

With this Library, 16bit timers have a frequency range from 1Hz to 2MHz. 8bit timers have a range from 31Hz to 2MHz. As the frequency becomes larger, the smaller the range power duties for a pin becomes. It is technically possible to push the frequency to 8MHz, but the range of possible power duties get stupidly small by that point. To be sure the frequency was correctly set, be sure to check the return value. If you don't want to sacrifice any 8bit PWM pins, don't call the initialize function for that timer, try changing the prescaler to manipulate frequency instead. There are many tutorials on how the prescaler affects timers and this library contains methods that make easier and less bug prone to manipulate. So far, I have tested this library on an Uno and a Mega. This library should be compatible with all Arduinos except the Leonardo and Due. If you have an Arduino that is not a Mega or Uno, please test it and tell me how it went. If somebody has an oscilloscope on hand to verify the frequencies being generated are correct, that would also be helpful.

For now, consider this library to be in beta. Developments on this library are described in later posts.
Here are some of the current features of this library:

  • Wraps timer specific properties (such as timer top and prescaler) with functions
  • Has pin based (timer agnostic) functions
  • Has functions for getting and setting frequency at the timer level and pin level
  • Has tools for measuring timer resolution at the timer level and pin level

The latest is version .05
link: Google Code Archive - Long-term storage for Google Code Project Hosting.

There are technically libraries out there that allow you to set the PWM frequency. They are, however, typically labeled as audio "tone" libraries. It doesn't matter if the library is designed for audio, it's still just a PWM library. I've written some of these libraries, some of which will output PWM signals at up to the megahertz range.

Tim