PWM frequency library

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.

2 Likes

I added a fix that removed a bug limiting 8 bit timers to 65535 Hz (I will let you guess what the problem was...) and I added an example sketch to the project. Both versions can be found at the same link provided above.

What's the deal with this not working on the Leonardo?

The Leonardo has a different CPU architecture. That means different timers with different properties that I would have to wrap.
So far, Arduino microcontrollers use three main architectures 'groups'. Arduino Mega and ADK are of the AVR mega 1280/1281/2560/2561 group, which are all identical except for the amount of memory they hold. The Leonardo uses ATmega32u4. And pretty much everything else uses 88/168/328 variants.
I have an Uno and a Mega, which means I was able to build and test for every architecture except the Leonardo. If there is enough interest in this project, I would be willing to try to get it working on the Leonardo. But I have no reliable way too test it in real life to make sure it works.

awesome library !

I have a question here.

my mega 2560 is connect to tlc5940 pwm chip. and it use timer 1 and timer 2.

according to the datasheet of mega 2560 pin 7 is using timer 4.

so i using a led and try to connect pin 7 and it is working (can see the different between 20hz to 20000hz while it is 20 hz the led dim and blinking. with 20000Hz led dim without blinking). but i want to know is the pin 7 still using timer 4? after i change the pin from default pin to pin 7.

#include <PWM.h>

//use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
int led = 7;                // the pin that the LED is attached to
int brightness = 0;         // how bright the LED is
int fadeAmount = 5;         // how many points to fade the LED by
int32_t frequency = 20000; //frequency (in Hz)

void setup()
{
  //initialize all timers except for 0, to save time keeping functions
  InitTimersSafe(); 

  //sets the frequency for the specified pin
  bool success = SetPinFrequencySafe(led, frequency);
  
  //if the pin frequency was set successfully, pin 13 turn on
  if(success) {
    pinMode(13, OUTPUT);
    digitalWrite(13, HIGH);    
  }
}

void loop()
{
  //use this functions instead of analogWrite on 'initialized' pins
  pwmWrite(led, brightness);

  brightness = brightness + fadeAmount;

  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ; 
  }     
  
  delay(30);      
}

I am sorry, it is not clear to me what you mean by 'default pin'. If you mean the timer the pin is connected to before and after the initialize function was called then yes, the timer does not change. On the mega, pin 11 is on timer 1, pin 9 is wired to timer 2, and pin 7 is wired to timer 4. That cannot be changed by software.

Hi,

very nice library it was really needed.
One question or suggestion, as far as I understand, it is not possible with your library to have more than 8 bit resolution for pwmWrite ?
For my application I need 10bits or so, do you see any way to implement that in you library ?

thanks for sharing, good job.

8 bit timers are 'capable' of 8 bit resolution, 16 bit timers are 'capable' of 16 bit resolution. For the sake of consistency, I stuck with 8 in this library. It didn't occur to me that there was any need to bump up the resolution. I will happy to add some methods when I get some time to do so within a few days. It should be noted, however, that this would only affect 16 bit timers.

Note: there is also one caveat you must associate with AVR timers and resolution. The resolution effectively decreases inversely with the frequency. At 1KHz you get ~13 bits of resolution. At 100 KHz, you get ~6 bits of resolution. At 1 MHz you get ~3 bits of resolution. This is a property of the timers on AVR CPUs and cannot be changed by software.

To check your resolution at a given frequency, set the frequency on the timer of your choice. The SetFrequency functions are aware of all of the variables, and will mathematically determine the method of creating the highest possible resolution. Then call TimerX_GetTop() and add 1. That will be your resolution in base 10 (decimal). Take Log base 2 of that and you can get your resolution in binary. In other words:
Resolution = LOG2(TimerX_GetTop() + 1).

Just out of curiosity; what do you need the resolution for, and what board are you using.

Edit: forgot the +1 in the original post

Hi,

thanks for your explanation. My application is about dimming power leds. Dimming is not linear at all, and for some reason, I cannot go near zero . I think it is because of integrated led driver, that must perform pwm internally. Anyway, I count get it working by using 16bits timer on an arduino Uno using LUT table to obtain linear fading. now I have to port to an arduino Mega, and your library is very "time saver" for me.

thank you.

I have working "high resolution" functions and an example, I will post it later today when I get the chance.

The code is now up. There are three new functions and an example sketch to explain how they work.
To be consistent with analogWrite(), pwmWrite() will always perform 8 bit pwm. If a higher resolution is necessary, use pwmWriteHR() instead.

void pwmWrite(uint8_t pin, uint8_t duty) 8-bit, 0 - 255
void pwmWriteHR(uint8_t pin, uint16_t duty) 16-bit, 0 - 65535

Unfortunately, resolution control is not that simple once custom frequencies come into play. If you modify the frequency on a timer, the resolution will change. The general rule of thumb is that the higher the frequency the lower the resolution. There are several variables that the SetFrequency functions wrap. They are aware of them and will mathematically determine the highest possible resolution at that given frequency. Although pwmWriteHR() accepts a 16 bit integer, it will automatically map to any timer resolution. To know whether the resolution is too low for your tolerances at a particular frequency, I have added two functions.

float GetPinResolution(uint8_t pin)
float TimerX_GetResolution() (replace X with a timer number)

These functions find the resolution in base 2/the number bits required to represent the resolution. Please note that both return floats, not ints; that is intentional. If you prefer to find the number of possible values instead of messing with binary, use TimerX_GetTop() and add 1 (which is the same thing but in base 10).

I added a sketch called PWM_lib_resolution_example to the project to demonstrate these functions and the relationship between timer frequency and resolution.
I have not been able to find enough time to exhaustively check this code for bugs, so if you find any please speak up.

Awesome library runnerup!

Wait, I can't verify my sketch as it says 'prescaler' has not been declared in the following line:

extern void		SetPrescaler_8(const int16_t timerOffset, prescaler psc);

What should I do?

Many thanks

I mean, I tried using the psalt and then it says that prescaler_alt hasn't been declared either? Am I modifying it incorrectly by just simply deleting ps_... values and the line of code in the previous reply?

Good work Ksshhs, you found a bug for me XD... but no, it was not the cause of your problem.
The library currently has a bug in the preprocessor directives. It calls the wrong internal SetPrescaller function for timer 2. I will publish version .04 to fix that right away.

I have no way of knowing what your problem is. For future reference, you should post the source you are working with, along with the type of board you are compiling for.
My guess is that you are trying to call either Timer0_SetPrescaler() or Timer2_SetPrescaler() explicitly and using the wrong syntax for the parameter.

Here is an example of setting the prescaller to 1024 on all of the mega's timers:

void setup()
{
        Timer0_SetPrescaler(ps_1024);
	Timer1_SetPrescaler(ps_1024);
	Timer2_SetPrescaler(psalt_1024);
	Timer3_SetPrescaler(ps_1024);
	Timer4_SetPrescaler(ps_1024);
	Timer5_SetPrescaler(ps_1024);
}

Same deal on the Uno and most other non megas except there are only 3 timers (0, 1, and 2) available. Attempting to use the others will give you a compiler error

For all possible prescaler parameters, look at how it it is defined in the header (you can also look at the first post in this thread):

enum prescaler
{
	ps_1	=	1,
	ps_8	=	2,
	ps_64	=	3,
	ps_256	=	4,
	ps_1024 =	5
};

//certain 8 bit timers read the CSn register differently
enum prescaler_alt
{
	psalt_1		=	1,
	psalt_8		=	2,
	psalt_32	=	3,
	psalt_64	=	4,
	psalt_128	=	5,
	psalt_256	=	6,
	psalt_1024	=	7
};

Don't worry about the values the enum elements are set to, they are used as bit masks and can only confuse humans.
Oh, and be sure to download the newest version of the library before you mess with timer 2.

pwmWriteHR is a good solution, I think.
I'll try that as soon as possible.

I'm ok it's a bit hard to deal with resolution. But things that was not possible, now are, so...

Thanks for taking on your time, it's very helpful.

Thanks for your reply runnerup, although I will have to call for your help once again as I am new to Arduino but the deadline for my project is fast approaching!! I am trying my best but am still getting compile errors, so I was hoping you could take a look at the source code I have written and with the knowledge that I am using an Arduino Uno and possibly you could spot what is going wrong!

 # include "PWM.h" 

//Initialize Motor 1
int InA1 = 8;
int InB1 = 12;
int PWM1 = 10;
int32_t frequency = 20000;

void setup() 

{  
  
   InitTimersSafe();
   bool success = SetPinFrequencySafe(PWM1, frequency);
  
   if(success){
   pinMode (InA1, OUTPUT);
   pinMode (InB1, OUTPUT);
   pinMode (PWM1, OUTPUT);}
 
}
 
void loop ()
{
  
  
  {//Motor Start Delay
       delay(1000);
       
   //Motor Direction
       digitalWrite(InA1, HIGH);
       digitalWrite(InB1, LOW); }
     
   
   //Motor Acceleration Control
       {for(int fadeValue = 0 ; fadeValue <= 76; fadeValue +=5){
         pwmWrite(PWM1, fadeValue);
       
         delay(100000); }
       }
       
   //Motor Run Time        
       delay(10000);
       
   //Motor Decceleration Control
       {for(int fadeValue = 76; fadeValue >= 0; fadeValue -=5){
          pwmWrite(PWM1, fadeValue);
          
          delay(100000); 
       }
       }  
         
   //Motor Stop Time
       delay(10000); 
  
}

Here is the error I am now getting. I have installed v4.0.

Many thanks!

 # include "PWM.h"

There shouldn't be a space between the '#' and include.

dxw00d got it, you are using the preprocessor incorrectly, but I see another bug in your code.
Pin 10 cannot be used for pwm in this library. That means:

if(success) //always skips this block, success is always false
{
   pinMode (InA1, OUTPUT);
   pinMode (InB1, OUTPUT);
   pinMode (PWM1, OUTPUT);
}//you have no else statement, you can't catch or deal with the error. Your program will continue on without dealing with this issue.

It is an avoidable property with Arduino's 8 bit timers. You can use pins 2, 3, 6, 7, 8, 11, 12, 44, 45, and 46. Pins 10 and 4 are lost for pwm output (they still work for digital input and output). In your case, since you use delay functions and the safe version of InitTimers(), you should avoid pin 5, since it is connected to timer 0.

also, look at the line

delay(100000);

that's an additional 100 seconds per iteration. Are you sure you want to do that?
And just one more thing. It appears you use a lot of curly brackets "{ ... }" where you don't need them. Generally they are used when going into scope, in the case of an if...else and for loop. Although the C language lets you put them in needless places, they will only confuse you and other readers (and potentially create local variable bugs). Your setup() and loop() have the same meaning as the following:

void setup()
{
	
	InitTimersSafe();
	bool success = SetPinFrequencySafe(PWM1, frequency);
	
	if(success){
		pinMode (InA1, OUTPUT);
		pinMode (InB1, OUTPUT);
		pinMode (PWM1, OUTPUT);
	}
	
}

void loop ()
{	
	//Motor Start Delay
	delay(1000);
	
	//Motor Direction
	digitalWrite(InA1, HIGH);
	digitalWrite(InB1, LOW);


	//Motor Acceleration Control
	for(int fadeValue = 0 ; fadeValue <= 76; fadeValue +=5){
		pwmWrite(PWM1, fadeValue);
		delay(100000);
	}

	//Motor Run Time
	delay(10000);

	//Motor Decceleration Control
	for(int fadeValue = 76; fadeValue >= 0; fadeValue -=5){
		pwmWrite(PWM1, fadeValue);
		delay(100000);
        }  
         
   //Motor Stop Time
       delay(10000); 
}

now which one is easier to read? The only differences are changes to indentation to match the scope, removing useless brackets, and moving the necessary closing brackets on to the next line (note: the indentation does look a bit exaggerated I was using a different editor that deals with tabs differently).
Hopefully this helped, good luck on your project.

This library looks to be a huge help, really appreciate the time. It really is silly that something doesn't exist like this with the stock set of libraries.

I have one issue I'm having getting started with it, that I could use some help on. I'm using a Nano v3, so basically the same thing as an Uno. Pins 5 and 6 associated with Timer 0, Pins 9 and 10 associated with Timer 1, Pins 3 and 11 associated with Timer 2.

I'm building a circuit that will manually control a Honda Insight's hybrid system. This is controlled by 3 control lines, with 2 of them being PWM signals with varying duty cycles. 1 needs to be 20kHz, and the other 2kHz. Therefor, the plan is to use Timer 1 and Timer 2.

When looking for a successful Frequency setting on the Timers, I believe I need to use Pins 10 and 3 on the respective timers. If I use 11 instead of 3, I do not get success for setting the frequency. The issue comes when I make the call to check the resolution of each pin.

Pin 10 (set at 20kHz) returns a resolution of 8.65
Pin 3 (set at 2kHz) returns a resolution of 0.00

If I reverse the pins:

Pin 10 (2kHz) returns a resolution 11.97
Pin 3 (20kHz) returns a resolution of 0.00

What would cause the 0 resolution on Timer 2?

EDIT:
Just checked and Timer 2 provides a frequency of 55555Hz after setting it at 20kHz. I played around with it and when setting it around 15kHz, it outputs almost correctly, except it returns slightly higher than set. Whenever I set it any higher than 15.7kHz, it starts reporting over double of what the set value is. For example, at 15.7kHz, it returns 31620Hz.

A pastebin of the output from your resolution example, with the pin changed to pin 3 and output from Timer2: As frequency increases, resolution will decrease...Frequency: 500 Hz Numbe - Pastebin.com

I was able to get your frequency method to report 20k, by setting this up manually:

  TCCR2A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS21);
  OCR2A = 50;
  OCR2B = 25;

The resolution is still reported as 0, but reports possible duties of 51.