Arduino Forum

Development => Other Software Development => Topic started by: runnerup on Aug 06, 2012, 01:37 am

Title: PWM frequency library
Post by: runnerup on Aug 06, 2012, 01:37 am
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:



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:


The latest is version .05
link: http://code.google.com/p/arduino-pwm-frequency-library/downloads/list
Title: Re: PWM frequency library
Post by: runnerup on Aug 12, 2012, 07:25 pm
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.
Title: Re: PWM frequency library
Post by: atronchi on Aug 13, 2012, 11:52 pm
What's the deal with this not working on the Leonardo?
Title: Re: PWM frequency library
Post by: runnerup on Aug 14, 2012, 01:23 am
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.
Title: Re: PWM frequency library
Post by: tonify on Aug 14, 2012, 12:59 pm
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.

Code: [Select]
#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);     
}

Title: Re: PWM frequency library
Post by: runnerup on Aug 14, 2012, 10:33 pm
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.
Title: Re: PWM frequency library
Post by: mgth on Aug 15, 2012, 09:21 pm
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.
Title: Re: PWM frequency library
Post by: runnerup on Aug 16, 2012, 01:33 am
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
Title: Re: PWM frequency library
Post by: mgth on Aug 17, 2012, 12:18 am
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.


Title: Re: PWM frequency library
Post by: runnerup on Aug 17, 2012, 02:36 pm
I have working "high resolution" functions and an example, I will post it later today when I get the chance.
Title: Re: PWM frequency library
Post by: runnerup on Aug 17, 2012, 05:56 pm
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.
Title: Re: PWM frequency library
Post by: ksshhs on Aug 20, 2012, 04:08 pm
Awesome library runnerup!
Title: Re: PWM frequency library
Post by: ksshhs on Aug 20, 2012, 05:10 pm
Wait, I can't verify my sketch as it says 'prescaler' has not been declared in the following line:

Code: [Select]
extern void SetPrescaler_8(const int16_t timerOffset, prescaler psc);

What should I do?

Many thanks
Title: Re: PWM frequency library
Post by: ksshhs on Aug 20, 2012, 05:40 pm
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?
Title: Re: PWM frequency library
Post by: runnerup on Aug 20, 2012, 09:27 pm
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:

Code: [Select]

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):
Code: [Select]

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.
Title: Re: PWM frequency library
Post by: mgth on Aug 21, 2012, 10:19 am
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.
Title: Re: PWM frequency library
Post by: ksshhs on Aug 21, 2012, 10:35 am
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!

Code: [Select]
# 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.

(http://i49.tinypic.com/fmi713.png)

Many thanks!
Title: Re: PWM frequency library
Post by: dxw00d on Aug 21, 2012, 10:55 am
Code: [Select]
# include "PWM.h"
There shouldn't be a space between the '#' and include.
Title: Re: PWM frequency library
Post by: runnerup on Aug 21, 2012, 02:50 pm
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:
Code: [Select]

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

Code: [Select]

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:

Code: [Select]

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.
Title: Re: PWM frequency library
Post by: rothnic on Sep 23, 2012, 07:30 pm
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: http://pastebin.com/8vgj6ZBn

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

Code: [Select]

  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.
Title: Re: PWM frequency library
Post by: runnerup on Sep 24, 2012, 01:18 am
I was able to reproduce the frequency errors for timer 2 and timer 1 (55555 when set to 20000 and 31620 and 15.7K) in Atmel Studio. Sounds like a truncation issue. I was not able to reproduce the resolution errors. I ran the code test code on my Uno and Atmel Studio it looks clean.

I might have something tomorrow afternoon (east coast USA time) for the frequency problem, I will keep looking into the resolution problem.
Title: Re: PWM frequency library
Post by: rothnic on Sep 24, 2012, 03:21 am

I was able to reproduce the frequency errors for timer 2 and timer 1 (55555 when set to 20000 and 31620 and 15.7K) in Atmel Studio. Sounds like a truncation issue. I was not able to reproduce the resolution errors. I ran the code test code on my Uno and Atmel Studio it looks clean.

I might have something tomorrow afternoon (east coast USA time) for the frequency problem, I will keep looking into the resolution problem.


Thanks, yeah not sure what is going on with the resolution reporting. I'll keep messing with it.

I did find a nice little free logic analyzer that hooks up to an arduino to test this stuff out. I confirmed that I'm seeing 2kHz on Timer1(Pin 10), and 55.556kHz on Timer2(Pin 3). http://i.imgur.com/aRGS8.png

If anyone comes across this and wants to check their PWM signals out, try this: http://letsmakerobots.com/node/31422 . I'm running it no problems with my Mega, but needed to use version 0.9.5 of the analyzer for it to work with the Arduino plugin.
Title: Re: PWM frequency library
Post by: runnerup on Sep 24, 2012, 04:00 am
Yay integer division!
...ehem

I found the bug, I will publish the patch tomorrow afternoon after I have more time to test it.
All 8 bit timers will be set to higher than expected frequencies when set to high frequencies (go figure). I haven't actually checked myself, but according to rothnic the threshold is somewhere between 15KHz and 16KHz.
Due to the nature of the this particular bug, it should not affect PWM duty, only frequency.
Again, I have no idea what is causing that bad resolution reading, my Mega and Uno have no trouble with it.
Title: Re: PWM frequency library
Post by: rothnic on Sep 24, 2012, 05:24 am

Yay integer division!
...ehem

I found the bug, I will publish the patch tomorrow afternoon after I have more time to test it.
All 8 bit timers will be set to higher than expected frequencies when set to high frequencies (go figure). I haven't actually checked myself, but according to rothnic the threshold is somewhere between 15KHz and 16KHz.
Due to the nature of the this particular bug, it should not affect PWM duty, only frequency.
Again, I have no idea what is causing that bad resolution reading, my Mega and Uno have no trouble with it.


Sounds good.

Right now I have the 2kHz frequency working ok, but there is an issue with the duty cycle. This is on the 16bit Timer, so with it set at 2kHz it returns 4000 from the Timer1_GetTop call. But, if I do a pwmWrite(10, 2000), I get a Duty cycle of 81.6% in this logic analyzer. This makes me doubt the hardware a bit.

I guess in the end I can get it working with a little trial and error, worst case. Looks like pwmWrite(10, 5000) gets me pretty close to 50%.
Title: Re: PWM frequency library
Post by: runnerup on Sep 24, 2012, 10:43 pm
Quote
if I do a pwmWrite(10, 2000), I get a Duty cycle of 81.6% in this logic analyzer


That's because the acceptable range for pwmWrite() is 0 - 255, or one unsigned 8 bit integer. You are truncating that int many times over with that second parameter and getting a junk duty cycle as a result.
pwmWrite() parameters are meant to mimic analogWrite() parameters. If you need more resolution, use pwmWriteHR(). It is described earlier in this thread.

This fix should solve your frequency issues, I still have no answer for the test program resolution issue. My Mega, my Uno, and Atmel studio simulators have no problem with it.

The latest version of the library as of this post is v .05. You can download it here:
https://code.google.com/p/arduino-pwm-frequency-library/downloads/list
Title: Re: PWM frequency library
Post by: rothnic on Sep 24, 2012, 11:31 pm

Quote
if I do a pwmWrite(10, 2000), I get a Duty cycle of 81.6% in this logic analyzer


That's because the acceptable range for pwmWrite() is 0 - 255, or one unsigned 8 bit integer. You are truncating that int many times over with that second parameter and getting a junk duty cycle as a result.
pwmWrite() parameters are meant to mimic analogWrite() parameters. If you need more resolution, use pwmWriteHR(). It is described earlier in this thread.

This fix should solve your frequency issues, I still have no answer for the test program resolution issue. My Mega, my Uno, and Atmel studio simulators have no problem with it.

The latest version of the library as of this post is v .05. You can download it here:
https://code.google.com/p/arduino-pwm-frequency-library/downloads/list


Ahh, yeah I was thinking about that while I was at work. Forgot to use the HR version. Didn't realize it was 0-255 for lower resolution frequencies as well. I'll try it out and add some results here in a bit.

Thanks again for your efforts.

Update:
Still have the 0 resolution problem on Timer2, and after looking at your code I assume there has to be some offset mismatch specific to this nano for some reason. No big deal though since I am getting the output I need: http://i.imgur.com/iwFcl.png . Both signals behaving as expected.
Title: Re: PWM frequency library
Post by: sinnaro on Nov 27, 2012, 12:08 am
For those that get here looking for how to change PWM frequency for the Due, you should look here for a solution: http://arduino.cc/forum/index.php/topic,131323.msg989728.html#msg989728

Basically, only pins 6-9 on the Due board are actual HWPWM and the other pins labeled as PWM are timer pins.

You can change the frequency of the PWM pins 6-9 with the following (changes the frequency for all the pins):
Code: [Select]
PWMC_ConfigureClocks(whatever_freq_you_want * 255 , 0, VARIANT_MCK)

I'm not sure how/if individual pin frequencies can be changed.

The same can be accomplished by changing
Code: [Select]
#define PWM_FREQUENCY 1000 for the pins 6-9 and
Code: [Select]
#define TC_FREQUENCY        1000 for the other PWM timer pins. These constants are defined in 'variant.h'.

Hope this helps someone along the road.
Title: PWM frequency library FOR Arduino Micro
Post by: Petit-Jean on Jan 07, 2013, 05:34 pm
Thank you runnerup (http://arduino.cc/forum/index.php?action=profile;u=38942) for this nice piece of work!

I have some questions for you, since I really need to expand this library for the Micro/Leonardo.
So that is what I will do, but maybe you can help me in the right direction.



Any hint is welcome.

Many thanks in advance!
Christophe aka Petit Jean
Title: Re: PWM frequency library
Post by: mxw8950 on Jan 08, 2013, 09:54 pm
Thank you so much for this library as it has been fantastic in helping me get a pump driver up and running.

I have a question regarding timers using the 328. I have noticed that the library functions do not allow you to set the frequency on TIMER2A and was wondering if there was a specific reason why the library would not allow you to set this timer as I can't really find a default use for TIMER2A that would interfere with any other arduino function.

Thanks,
-matt
Title: Re: PWM frequency library
Post by: MaxHeadroom on Jan 17, 2013, 10:13 am
Hi
I'm not quite clear as to these statements:
Quote
Has pin based (timer agnostic) functions
Has functions for getting and setting frequency at the timer level and pin level


I want to use your library to up the frequency of the PWM on my motor control project (motors are noisy) on a Uno. It is a twin motor control so I use pins 5, 6 for one and pins 9,10 for other.
Pins 5, 6 are timer0 and I don't want to mess with that timer.
So the next step would be to change it to pins 3, 11 to use the other timer. This would mean hacking my shield.
And that is why I don't understand the above. Does this mean I can map the PWM output to any pin?

I haven't used your library yet, just want to clear this first.

Thanks.
Title: Re: PWM frequency library
Post by: Tenta on Jan 26, 2013, 09:06 pm
Hi,

where can I look up which timer on the Mega 2560 is connected to which pin?
Also how can I turn PWM Pin 2 & 3 into phase correct mode?
[Edit]
I think it should work like this:
Code: [Select]
TCCR3A = _BV(COM3A1) | _BV(COM3B1) | _BV(WGM30);
TCCR3B = _BV(CS32);

One last question how can I invert the signal?


Thank you
Title: Re: PWM frequency library
Post by: runnerup on Jan 27, 2013, 10:11 pm
Sorry, I haven't looked at this thread in a while. I updated the original post to explicitly say this library does not support the Due. I don't think I will add support because I don't own a Due, and it appears to have some built library support already.

Petit Jean:

Quote

Thank you runnerup for this nice piece of work!

I have some questions for you, since I really need to expand this library for the Micro/Leonardo.
So that is what I will do, but maybe you can help me in the right direction.

In your estimation, can I better build of of ATimerDefs or BTimerDefs?
Do you have any idea how I could implement the difference in structure of the new 8 - 10 - 16 bit pins and fast PWM?
I want to change some of the timer--pin assignments for my project. Is that something that you think will work correctly with the construction you used for the library?
I will find my way in the end, but can you give me some places to start looking for the registers and stuff?

Any hint is welcome.


ATimerDefs or BTimerDefs are simply files that the preprocessor will include depending on the avr architecture the user compiles his code for.
If you want to implement different PWM modes, look at the specs sheet (http://www.atmel.com/Images/doc2549.pdf). Table 17-2 on page 148 describes which bits to manipulate to set each of the modes for the 16 bit timers.


mxw8950:

Quote

Thank you so much for this library as it has been fantastic in helping me get a pump driver up and running.

I have a question regarding timers using the 328. I have noticed that the library functions do not allow you to set the frequency on TIMER2A and was wondering if there was a specific reason why the library would not allow you to set this timer as I can't really find a default use for TIMER2A that would interfere with any other arduino function.

Thanks,
-matt


You don't set the frequency on TIMER2A because that is a channel, not a timer. A single pin is attached to timer2a, multiple pins are wired to a timer. When you set a frequency, it sets the entire timer and all of the pins wired to that timer are affected. If channel A on timer 2 is not working, then channel B probably won't work either. Can you verify that?

MaxHeadroom:

Quote
I want to use your library to up the frequency of the PWM on my motor control project (motors are noisy) on a Uno. It is a twin motor control so I use pins 5, 6 for one and pins 9,10 for other.
Pins 5, 6 are timer0 and I don't want to mess with that timer.
So the next step would be to change it to pins 3, 11 to use the other timer. This would mean hacking my shield.
And that is why I don't understand the above. Does this mean I can map the PWM output to any pin?


No, my wording is just a little confusing. By that I meant the caller (of that specific function) does not need to have any knowledge about which timer that pin is connected to since the function will figure that out for them. The pins are hardwired to the respective timer and cannot be changed. If you aren't using your uno for anything that requires timing functions (such as delay() and millis()) then you can use timer 0 without any problems.

Tenta:

Quote
where can I look up which timer on the Mega 2560 is connected to which pin?
Also how can I turn PWM Pin 2 & 3 into phase correct mode?


you can look it up here:

















timer# and channel   pin #
TIMER3B2
TIMER3C3
TIMER0B4
TIMER3A5
TIMER4A6
TIMER4B7
TIMER4C8
TIMER2B9
TIMER2A10
TIMER1A11
TIMER1B12
TIMER0A13
TIMER5C44
TIMER5B45
TIMER5A46


The library initializes timers to phase and frequency correct PWM. I do not know what you mean by phase correct because the timers have many 'phase correct' settings. I advise you to look at table 17-2 on page 148 and table 17-5 on page 160 in the specs sheet (http://www.atmel.com/Images/doc2549.pdf). The code you listed will not set the correct waveform generation mode. Com bits determine whether the pin is connected/how the pin is manipulated by the timer. Waveform generation mode is a timer setting, not a pin setting. You should manipulate the WGM bits instead.
Title: Re: PWM frequency library
Post by: Tenta on Jan 28, 2013, 04:07 pm
Thank you so much for the fast answer and your great work!
If I understood you right, your library sets the timer in to a phase and frequency corret pwm instead of fast pwm?
Title: Re: PWM frequency library
Post by: runnerup on Jan 29, 2013, 03:48 pm
Code: [Select]
If I understood you right, your library sets the timer in to a phase and frequency corret pwm instead of fast pwm?
Yes. Arduino libraries use fast PWM, this library sets timers to phase and frequency correct PWM.
Title: Re: PWM frequency library
Post by: Michael_XXX on Feb 08, 2013, 07:52 pm
I am new to arduino. So I do not fully understand the code.

The main point is I want to ask is these function can change the PWM frequency up to 2MHz by calling the function of "pwmWrite()" and "SetPinFrequencySafe()" ?

Then, what is the resoluation of this frequency, 8 bits or 16bits?

Thanks.
Title: Re: PWM frequency library
Post by: ZioWally on Feb 08, 2013, 08:14 pm
HELLO!

I tried PWM.h with arduino uno, good work!

my code adjusts the speed of a fan by trimmer on in analog input.

The fan is driven by a MOSFET connected to pin3. Everything works fine!

a few questions:

on pin3: if I use a low frequency I hear a whistle.
if I raise the frequency does not whistle anymore, okay! (My frequency counter reads Hz that i set in my code)

if I run the same code on PIN11:
the fan does not whistle, even if imposed 490Hz, my frequency counter reads no value (0.00 Hz), but the fan works fine.



why there is this difference between pin3 and PIN11?

I double checked the code and connections in the shield, and everything is ok

I am Italian, I apologize for my English, many thanks

Walter
Title: Re: PWM frequency library
Post by: ZioWally on Feb 09, 2013, 03:35 pm
sorry,

I double-checked,

pin3 on the frequency counter reads 490Hz like i set the code,

on PIN11 reads a value greater than 50,000 Hz, over the range of reading of my frequency counter

Why this difference between pin3 and pin11?
Title: Re: PWM frequency library
Post by: sparkylabs on Apr 06, 2013, 05:57 pm
Can the PWM be turned on or off ? do i just set it to "0" ?
Title: Re: PWM frequency library
Post by: carbon_adam on Apr 15, 2013, 01:57 pm
one question, how do I determine the PWM range fora a given pin with a modified frequency.  Take for example my sketch below that uses 20khz on pin 9.  Normally the values 0 256 work fine without the mod but I had to raise it to 256 to 512..it doesn't go as high as 512 more like in the 400 range..just want to know what I'm missing to understand that and if there is an easy calculation.

Code: [Select]
// simple move forward and backward one motor on the l298n using pins 12 13 9/ 9 being PWM
#include <PWM.h>
int ENA = 9;
int IN1 = 12;
int IN2 = 13;
int32_t frequency = 20000; //frequency (in Hz)

void setup ()
{
 Serial.begin(9600);
 InitTimersSafe();
 bool success = SetPinFrequencySafe(ENA, frequency);
 pinMode (ENA, OUTPUT);
 pinMode (IN1, OUTPUT);
 pinMode (IN2, OUTPUT);
}

void test_motor_1 ()
{
 for (int i = 256; i < 512; i++)
 {
   digitalWrite (IN1, HIGH);
   digitalWrite (IN2, LOW);
   analogWrite (ENA, i);
   delay (30);
   Serial.println(i);
 }

 delay (100);
 digitalWrite (IN1, LOW);
 
 for (int i = 256; i < 512; i++)
 {
   digitalWrite (IN1, LOW);
   digitalWrite (IN2, HIGH);
   pwmWrite  (ENA, i);  //was analogWrite
   delay (30);
  Serial.println(i);
 }

 delay (100);
 digitalWrite (IN2, LOW);
}

void loop()
{
 test_motor_1();
}
Title: Re: PWM frequency library
Post by: teckel on Apr 15, 2013, 04:58 pm

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: http://code.google.com/p/arduino-pwm-frequency-library/downloads/list


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
Title: Re: PWM frequency library
Post by: sparkylabs on Apr 23, 2013, 11:09 pm
Do you still need someone to verify correct frequencies ? I set 100 Hz and got 99.6995 Hz so I'm guessing your pretty spot on.
Title: Re: PWM frequency library
Post by: freak174 on Apr 29, 2013, 12:49 am
Any thoughts regarding why you can't use digital pin 11 with timer2, using arduino uno? The oscilloscope doesn't output anything
Title: Re: PWM frequency library
Post by: TanHadron on Apr 29, 2013, 06:00 am
Quote
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 gigahertz range.


This interests me.  Particularly the part about the gigahertz range.  I haven't heard of this before.  Could you point me to somewhere that explains how this is done?
Title: Re: PWM frequency library
Post by: sparkylabs on Apr 29, 2013, 06:56 pm
The UNO runs at 16MHz so at best you will get 16MHz with a 50% duty, gigaherz is pure imagination.
Title: Re: PWM frequency library
Post by: TanHadron on Apr 29, 2013, 07:08 pm
That is what I had thought, but if it isn't a typo... if it's possible...

3.21 Jigahertz!  Tom!
Title: Re: PWM frequency library
Post by: teckel on Apr 29, 2013, 07:21 pm

Quote
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 gigahertz range.


This interests me.  Particularly the part about the gigahertz range.  I haven't heard of this before.  Could you point me to somewhere that explains how this is done?


Sorry, must have been drunk, I meant MEGAhertz, not gigahertz.

One of my tone libraries (toneAC) does PWM control of two pins alternating at up to 2.66 MHz with an ATmega running at 16MHz.

Official site (https://code.google.com/p/arduino-tone-ac/)
Arduino Playground (http://playground.arduino.cc/Code/ToneAC)
Support forum (http://arduino.cc/forum/index.php/topic,142097.0.html)

Sorry about the confusion.

Tim
Title: Re: PWM frequency library
Post by: breslopez on May 10, 2013, 11:52 pm
Hi!!
I just want to say, thanks for the library!!!, it seems to be very helpful, because, as you said, you did found a necessity, and well, you are now giving us a solution... Well, then, I'm an Arduino begginer ^_^, and I'm developing some project that involves the use of Ardu...and also the PWM management, thus, its frequency.
I did download your library, but, when I compile the first example, in the IDE message area says:
"PWM_lib_example.cpp: In function 'void setup()':
PWM_lib_example:23: error: 'InitTimersSafe' was not declared in this scope
PWM_lib_example:26: error: 'SetPinFrequencySafe' was not declared in this scope
PWM_lib_example.cpp: In function 'void loop()':
PWM_lib_example:38: error: 'pwmWrite' was not declared in this scope"

Also I was reading some comments, that it actually works perfectly =(...what you think could be the problem?? It seems like the IDE does not detect the #include <PWM.h>...
Thanks!!
Title: Re: PWM frequency library
Post by: runnerup on May 17, 2013, 08:49 am

Hi!!
I just want to say, thanks for the library!!!, it seems to be very helpful, because, as you said, you did found a necessity, and well, you are now giving us a solution... Well, then, I'm an Arduino begginer ^_^, and I'm developing some project that involves the use of Ardu...and also the PWM management, thus, its frequency.
I did download your library, but, when I compile the first example, in the IDE message area says:
"PWM_lib_example.cpp: In function 'void setup()':
PWM_lib_example:23: error: 'InitTimersSafe' was not declared in this scope
PWM_lib_example:26: error: 'SetPinFrequencySafe' was not declared in this scope
PWM_lib_example.cpp: In function 'void loop()':
PWM_lib_example:38: error: 'pwmWrite' was not declared in this scope"

Also I was reading some comments, that it actually works perfectly =(...what you think could be the problem?? It seems like the IDE does not detect the #include <PWM.h>...
Thanks!!


The compiler is telling you that it can't find the functions you are calling.
Assuming your includes are correct (which is the case if you are using an example), then you didn't add the library to the 'libraries' folder.

If you don't understand how libraries work in the Arduino environment try looking at this: http://www.arduino.cc/en/Hacking/Libraries
Title: Re: PWM frequency library
Post by: breslopez on May 23, 2013, 11:25 pm
Hi, thank you so much for your help, I already solve the problem....now, I'm traying to manipulate the "frequency" value from the Serial monitor...but I can't make it work, here's the code:
PD: Any help, THANKS!!!


/************************** TEC -2013 **************************
   
Este sketch es una variacion del PWM_lib_example de la biblioteca PWM,
donde se controla la frecuencia desde el monitor serial del IDE,
dando con ello un poco mas de practicidad, y mayor manejo sobre la
frecuencia deseada.

********************************************************************
*/

#include <PWM.h>

int brightness = 0;     //how bright the LED is.
int fadeAmount = 5;     //how many points to fade the LED by

void setup()
{
  //Inicializa todos los timers del Arduino, excepto el 0, para mantener las funciones de tiempo del micro
  Serial.begin(9600);
  InitTimersSafe(); 
 
}

void loop()
{
  int32_t frequency;
  if (Serial.available())
  {   
   
    frequency = Serial.read();
    SetPinFrequency(led, frequency);
   
  }
  pwmWrite(led, brightness);

  brightness = brightness + fadeAmount;

  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }     
 
  delay(30);   
   
  }
Title: Re: PWM frequency library
Post by: sparkylabs on Jun 12, 2013, 01:54 pm
I have done the following program (as initial steps for a thermostat program)

Code: [Select]

#include <PWM.h>



int T;
int32_t frequency = 500; //initialize the pwm output at 100Hz

void setup(){
 InitTimersSafe();
 SetPinFrequencySafe(11, frequency);
}


void loop(){

T = analogRead(0);

pwmWrite(11, 50); // write the duty to the output

delay(2000);

}


Nothing happens, other than the output being full on. I can't use the standard PWM as it makes the fan (and powersupply transformer) hum. Mind you even the standard analogwrite has stopped working or does the library do that ?
Title: Re: PWM frequency library
Post by: inketu on Jun 28, 2013, 02:21 pm
I only can said thanks runnerup!
Title: Re: PWM frequency library
Post by: Chino76 on Aug 23, 2013, 10:22 pm

Hi, thank you so much for your help, I already solve the problem....now, I'm traying to manipulate the "frequency" value from the Serial monitor...but I can't make it work, here's the code:
PD: Any help, THANKS!!!


/************************** TEC -2013 **************************
   
Este sketch es una variacion del PWM_lib_example de la biblioteca PWM,
donde se controla la frecuencia desde el monitor serial del IDE,
dando con ello un poco mas de practicidad, y mayor manejo sobre la
frecuencia deseada.

********************************************************************
*/

#include <PWM.h>

int brightness = 0;     //how bright the LED is.
int fadeAmount = 5;     //how many points to fade the LED by

void setup()
{
  //Inicializa todos los timers del Arduino, excepto el 0, para mantener las funciones de tiempo del micro
  Serial.begin(9600);
  InitTimersSafe(); 
 
}

void loop()
{
  int32_t frequency;
  if (Serial.available())
  {   
   
    frequency = Serial.read();
    SetPinFrequency(led, frequency);
   
  }
  pwmWrite(led, brightness);

  brightness = brightness + fadeAmount;

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



Hi! I have the same prolem as you. What did you do to solve it?
Title: Re: PWM frequency library
Post by: arduinoman7 on Sep 12, 2013, 10:49 pm


Hi, thank you so much for your help, I already solve the problem....now, I'm traying to manipulate the "frequency" value from the Serial monitor...but I can't make it work, here's the code:
PD: Any help, THANKS!!!


/************************** TEC -2013 **************************
   
Este sketch es una variacion del PWM_lib_example de la biblioteca PWM,
donde se controla la frecuencia desde el monitor serial del IDE,
dando con ello un poco mas de practicidad, y mayor manejo sobre la
frecuencia deseada.

********************************************************************
*/

#include <PWM.h>

int brightness = 0;     //how bright the LED is.
int fadeAmount = 5;     //how many points to fade the LED by

void setup()
{
  //Inicializa todos los timers del Arduino, excepto el 0, para mantener las funciones de tiempo del micro
  Serial.begin(9600);
  InitTimersSafe(); 
 
}

void loop()
{
  int32_t frequency;
  if (Serial.available())
  {   
   
    frequency = Serial.read();
    SetPinFrequency(led, frequency);
   
  }
  pwmWrite(led, brightness);

  brightness = brightness + fadeAmount;

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



Hi! I have the same prolem as you. What did you do to solve it?


I'm not sure how the other guy solved it. But this is how I solved it:
read http://arduino.cc/en/Guide/Libraries thoroughly
the library .h and/or .cpp files should be in their own folder and no more than one directory level deep. see the description on the bottom of the page i linked to.
once I rearranged my files, it worked.
Just make sure that your .h or .cpp file is in its own folder in the library folder, and not in subdirectories under its own folder
Title: Re: PWM frequency library
Post by: Docedison on Sep 13, 2013, 06:13 am
for 'local' h and cpp files the format is #include "myFile.h" instead of  #include <myFile.h>.. When I have library issues I move everything to the sketch folder and change the left and right 'arrows' to double quotes for the included files that are in the sketch folder... Works for me quite well, YMMV...

Doc
Title: Re: PWM frequency library
Post by: ADI89 on Oct 09, 2013, 05:31 pm
Hi..
I am getting an error   InitTimersSafe() was not declared in this scope while running this code .
Code: [Select]
#include "PWM.h"

//use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
int led = 9;                // 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 = 35; //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, turn pin 13 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 have already added the PWM frequency library still i am getting the error.
I am using Arduino 1.0.5 version
Title: Re: PWM frequency library
Post by: ADI89 on Oct 10, 2013, 06:31 am
Some one please help me...
Title: Re: PWM frequency library
Post by: krgoodwin on Nov 19, 2013, 10:21 pm
I'm trying to use this library to create a variable frequency quadrature output. I have confirmed I can set two outputs with the same frequency and different duty cycles but is there a way to offset on output by 1/2 pulse width? I am an arduino/programming/microcontroller noob. I tried spacing pwmWrite()s out with a delay() but it did not work :(


Some one please help me...


Kind of an old post and you may have figured this out but I compiled your code just fine. Double check your library was added properly.
Title: Re: PWM frequency library
Post by: cr93 on Dec 18, 2013, 08:23 pm
Hey guys, i am trying to control a dc motor with the pwm library (Arduino mega 2560) but the frequency that is generated it's too low because the motor doesn't move. I tried with 20KHZ frequency and didn't work. Here is my code:

#include<PWM.h>
int motor = 11 , valor_adc , tension;
int32_t frequency = 20000;
void setup(){
InitTimersSafe();
bool success = SetPinFrequencySafe(motor,frequency);
}
void loop(){
valor_adc=0;
valor_adc=analogRead(A0);
tension=valor_adc/4;
pwmWrite(motor,tension);
delay(30);
}
Title: Re: PWM frequency library
Post by: jay123 on Jan 27, 2014, 02:08 pm
Hi guys,

I did post in another area of the forum, but in hindsight really should have posted here.

I'm not sure how I go about getting the thread moved, so thought I would post a very brief summary:

I have an Uno and need to output two squarewaves - one at 3040Hz and one at 2010Hz. I'm having problems doing it using this library and must be doing something really stupid!

Anyway, the post is here: http://forum.arduino.cc/index.php?topic=213416.0 (http://forum.arduino.cc/index.php?topic=213416.0)

Thanks Jay :)
Title: Re: PWM frequency library
Post by: Ess_El_Emm on Jan 29, 2014, 02:10 am
Thank you very much for this library runnerup. I am making a project where I will need more than the normal 256 steps of PWM resolution, and this is exactly what I needed.

One question though, I'm a little confused by why the resolution has to decrease as frequency increases. Is this an actual limitation having to do with the clock speed of the chip and how quickly it runs through the timers?

You said earlier it had to do with the way the library is set up to allow variability of both the resolution and the frequency. Does this mean that if I manually set the registers in my program that I could achieve the full 16 bits of resolution that the 16 bit timers are capable of? I really don't care much about changing the frequency, just the resolution.

The more resolution the better for this project.
Title: Re: PWM frequency library
Post by: Skewb on Jan 29, 2014, 03:56 am
Hi, I have some code that uses this awesome library to independently control 3 computer fans via their pwm wires at 25khz using an Arduino Uno. Pins 3, 9, and 10 are currently used.
I am an arduino noob and this code was not written by me though. I have been trying to understand how this pwm and timing stuff works, but am still having trouble understanding.
Is there another pin I can use to independently control a 4th pwm fan without messing things up with the other arduino functions?

Thanks.
Title: Re: PWM frequency library
Post by: Ess_El_Emm on Jan 29, 2014, 12:49 pm
Ok, I have a another question now that I've played around with this library a little.

Looking at that chart that is shown in the serial monitor for what the maximum resolution is for a given frequency, it doesn't seem to be a steady correlation where resolution decreases as frequency increases. From 1Hz to 131Hz it actually appears that the maximum resolution increases. It peaks at 131Hz, and then goes down from there. Is that accurate? I don't understand why the maximum resolution goes up to a point and then starts going back down. Is 131Hz really the frequency to use to achieve the highest resolution?
Title: Re: PWM frequency library
Post by: utensil_tragedy on Jan 29, 2014, 04:32 pm
Hello,
This seems like it is a very useful library, but I am having trouble with it.

I imported the library and loaded up one of the examples - PWM_lib_example.  It is curious that some commands , such as
" InitTimersSafe();" do not turn orange, as if the software does not recognize it as a legitimate comman
d. I have seen examples on the internet where the line, in fact is orange.
The compiler comes up with several errors, such as:

PWM_lib_example:24: error: 'InitTimersSafe' was not declared in this scope

The reason I find this curious, is that I am using the example provided with the library, without modifying the code, and it doesn't verify. Am I doing something wrong?  Could the fact that I am on a Mac have anything to do with it?

*UPDATE*

After checking it on two Macs and getting the same problem I tested it on a Windows machine.
The command still didn't turn orange, but the out-of-the-box example compiled.
Therefore it might just be a Mac thing....

Title: Re: PWM frequency library
Post by: oreo18 on Feb 11, 2014, 04:06 am
I am new and trying to use this, I get an error

...document\arduino/libraries/PWM\BtimersDefs.h: 58 eroor: 'int16_t' does not name a type.
it says that for line 58 and 59.

clues?
Title: Re: PWM frequency library
Post by: imdafaddah on Feb 11, 2014, 02:24 pm
I just discovered this library and installed its latest version. I, too, have the same problem. The out-of-the-box example does not verify clean. there are three errors all relating to undeclared variables.
WASSUP??
Title: Re: PWM frequency library
Post by: ena123 on Feb 20, 2014, 09:45 pm
hi i am using this same library in arduino uno to generate 50Hz at a pwm pin. but i need the same signal to be generated at 4 pwm pins. can i simply use the same code to generate 50 Hz on 4 pwm pins, because different pins are associated with different timers, (8 bit or 16 bit) so will it be okay if i use same code?
Title: Re: PWM frequency library
Post by: ena123 on Feb 20, 2014, 09:52 pm
hi i am using this same library in arduino uno to generate 50Hz at a pwm pin. but i need the same signal to be generated at 4 pwm pins. can i simply use the same code to generate 50 Hz on 4 pwm pins, because different pins are associated with different timers, (8 bit or 16 bit) so will it be okay if i use same code?
Title: Re: PWM frequency library
Post by: ece_jm on Mar 03, 2014, 10:42 am

I just discovered this library and installed its latest version. I, too, have the same problem. The out-of-the-box example does not verify clean. there are three errors all relating to undeclared variables.
WASSUP??


I had the same problem at first.

That is because the examples are outside the actual PWM library folder. Just cut the contents of the PWM library such as PWM.h, keywords and the utility folder and paste it outside the PWM folder, restart your arduino, it should be fine
Title: Re: PWM frequency library
Post by: linkstatic on Mar 04, 2014, 01:40 pm
Can anyone tell me the right pins for PWM in ardiuno R3 uno? Cause last night i set the frequency to pin 5 at 1000 Hz but it was giving me 5000 Hz. Does anyone know about this issue? By the way I am not sure it was pin 5 but it was some pin which was giving out 5000 Hz. I checked it on a digital oscilloscope and I am sure i was giving it 1000 Hz.

Further more I will post a reply for Ardiuno Uno R3 right pins tomorrow after I have checked all pins. As we all know that pwm is used for motors but the actual pwm is given to a H-bridge and most H-bridges have a certain frequency at which they operate. If a higher frequency is given the h-bridge becomes unstable and may cause the frequency generator to fry. Well my h-bridge is sensitive as I have made it myself for 24V motors/5A. I will post the pins and their responses tomorrow after I have checked all the pins. Will post it with pictures.
Title: Re: PWM frequency library
Post by: DavidEAQ on Mar 19, 2014, 04:05 pm

Hi, thank you so much for your help, I already solve the problem....now, I'm traying to manipulate the "frequency" value from the Serial monitor...but I can't make it work, here's the code:
PD: Any help, THANKS!!!


/************************** TEC -2013 **************************
   
Este sketch es una variacion del PWM_lib_example de la biblioteca PWM,
donde se controla la frecuencia desde el monitor serial del IDE,
dando con ello un poco mas de practicidad, y mayor manejo sobre la
frecuencia deseada.

********************************************************************
*/

#include <PWM.h>

int brightness = 0;     //how bright the LED is.
int fadeAmount = 5;     //how many points to fade the LED by

void setup()
{
  //Inicializa todos los timers del Arduino, excepto el 0, para mantener las funciones de tiempo del micro
  Serial.begin(9600);
  InitTimersSafe(); 
 
}

void loop()
{
  int32_t frequency;
  if (Serial.available())
  {   
   
    frequency = Serial.read();
    SetPinFrequency(led, frequency);
   
  }
  pwmWrite(led, brightness);

  brightness = brightness + fadeAmount;

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



Hi, could you explain how did you solve your problem please?
I'm having the same problem and I have loaded the library with the tool of the IDE.
Also I have noticed that there's no PWM.cpp file. I'm a beginner at this and don't know if it would be the reason.
Title: Re: PWM frequency library
Post by: tigerbomb8 on Mar 23, 2014, 05:29 pm
Is anyone able to modify this to work on an attiny85
Title: Re: PWM frequency library
Post by: abbefaria on Mar 28, 2014, 11:34 pm
Wonderful library!! Very much needed!
I'm curious as to whether there is any way it can be used to control PWM frequency of two pins independently. From what I've discovered, I'm only able to successfully initialize frequency when it's using pin 9 or 10 (assuming you used timer 1). Would it be possible to use your library to have one PWM pin set to, say, 600Hz, and another pin set to 700Hz?
Thanks again!

As an edit: I played around with this a bit more and found something curious. Timer2 is tied to pins 3 and 11, while Timer1 is tied to pins 9 and 10 on my Uno. So, I tried making pin 11 600Hz and pin 10 700Hz with the library. Pin 10 initialized just fine, but pin 11 would not give me a true return (SetPinFrequencySafe). Switched to pin 3 instead of 11 and it worked like a charm. Anybody know what gives?

Also, is there an easy way to directly measure the number of pulses that occur between calling pwmWrite and stopping it? Obviously I could do math with the elapsed time and frequency, but getting some empirical data would be just that much better.
Title: Re: PWM frequency library
Post by: Rickmc3280 on Apr 04, 2014, 04:30 am
Thank you for the library. 

I used your example to try to use Scope to test the signal coming out and this is what i got

https://www.youtube.com/watch?v=6E7Llc4NxLU&feature=youtu.be

it has a few spikes and the amplitude changes greatly.  What would I need to do to...:

1) Control the speed using a program on my computer?
2)Fix the PWM signal to be a constant 89hz with a controlled duty cycle that I can control by clicking on buttons or something of the like?

the code I used is:
Quote
/*

Mimics the fade example but with an extra parameter for frequency. It should dim but with a flicker
because the frequency has been set low enough for the human eye to detect. This flicker is easiest to see when
the LED is moving with respect to the eye and when it is between about 20% - 60% brighness. The library
allows for a frequency range from 1Hz - 2MHz on 16 bit timers and 31Hz - 2 MHz on 8 bit timers. When
SetPinFrequency()/SetPinFrequencySafe() is called, a bool is returned which can be tested to verify the
frequency was actually changed.

This example runs on mega and uno.
*/

#include <PWM.h>

//use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
int led = 9;                // the pin that the LED is attached to
int brightness = 0;         // how bright the LED is
int speedcontrol = 5;         // how many points to fade the LED by
int32_t frequency = 89; //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, turn pin 13 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 + speedcontrol;

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


While I know its not right code, I wanted to test to see if it was getting a solid 89hz, which it was getting 89, but not solid (as in it spiked to above 200hz) possibly because of the programming not being right?
Title: Re: PWM frequency library
Post by: Rickmc3280 on Apr 07, 2014, 08:36 pm
If this frequency library does not work for you... Try this from a previous thread.  I have spent weeks trying to figure this stuff out...

Quote
I believe that there is a lot of confusion as to what the original author was trying to say.

According the the library TimerOne.h you can set certain pins to do whatever frequency you want (within capability of the board).

He is referring to this - http://playground.arduino.cc/Code/Timer1


using the coding from the website directly I had a lot of problems.  You have to download the timer files, leave them in the zip and put them directly into the libraries folder, no subfolders, dont extract them.  Once you are done doing this open up your sketch and import the libraries (ZIP FILE NEED TO BE IN THE LIBRARIES FOLDER) - I say all caps because I messed up several times and once I did this, everything worked perfectly.  then... "#Include <TimerOne.h> which you type in or click "Sketch" and Import Library --> click file and it will automatically add it.  

Mine looks like this
Quote

#include <TimerOne.h>

void setup() {
 // put your setup code here, to run once:
pinMode(9, OUTPUT);
Timer1.initialize(11230); // Intialize timer1, and set a 89hz frequency
Timer1.pwm(9,300); // setup pwm on pin 9, with a 50% duty cycle

}

void loop() {
 // put your main code here, to run repeatedly:
 
}


** In my sketch it says 50% Duty cycle in the notes but right now its actually at something else i just didnt change the notes on it.  It is using 10 bits so instead of 255 its like 1054 or something like that.

** Also
Figuring out HERTZ

  • go to: http://www.unitjuggler.com/convert-frequency-from-Hz-to-ms(p).html

  • Enter in desired hertz and it outputs how many milliseconds you need

  • take your milli seconds and conver them to microseconds by going to google and saying "convert milliseconds to microseconds"  it will then give you a google calculator and does the calculations for you

  • Use these calculations in your sketch, for example mine says 11230 - that is the microseconds needed to create an 89hz frequency because herz is how many cycles per second the signal is 1000000(1 second in Microseconds) / 11230 = 89.04 hz



AND it works.  My pin 9 is outputting an 89hz frequency.  

I could not be more excited.  

The the original Author, I hope you got it working... I dont know anything about creating advanced algorithms, but I hope this helps.


The arduino CAN make its own PWM frequency and is not limited like most of the posters have said.  Using the Timer1 for Uno and Timer3 for Mega, you can unlock the PWM potential :)   Hope this helps someone.  
Title: Re: PWM frequency library
Post by: arduinoNate on Apr 24, 2014, 12:26 pm
It looks like this library uses Macros to set the frequency.

If I'm reading this correctly, that means I can not change frequency 'in the loop'.

Does anyone know of a way to change frequency and duty cycle after compile time? Or do I have to port this library to not use Macros/precompiler directives?
Title: Re: PWM frequency library
Post by: Jimbowat on Aug 21, 2014, 07:30 am
Hi thanks for a great library i find it works well on the uno. I am varying the frequency and pulse width by reading 2 pots on the analog inputs and mapping that reading to suit the registers for frequency and pulse width. I am using pin 9 and 10 and invert 10 also control its pulse width with another pot.  Great library.
Title: Re: PWM frequency library
Post by: alegorosito on Oct 11, 2014, 09:12 pm
Hi, a simple question. Can I have 4 outputs with high resolution on a Arduino UNO?
Excellent library runnerup. Thank you!
Title: Re: PWM frequency library
Post by: patericko88 on Nov 20, 2014, 05:49 am
Anyone know why pin 11 on timer2 doesn't work?

All the rest work great.

I'm using the Uno.

Cheers
Title: Re: PWM frequency library
Post by: liooon03 on Nov 25, 2014, 03:27 am
hallo !
i'm using the arduno uno r3
if iwant to run the sevro motor (hg-kr053) and driver is Mitsubishi mr-j4-10a
how do i run this motor by arduino ?
      _________   __20K Hz
     /              \
    /                \
   /                  \
  /                    \
 rising time 0.2s and run 1s (20K Hz) down time 0.2s
and reten is the same.

i need the code!
Title: Re: PWM frequency library
Post by: ross4435897 on Nov 25, 2014, 09:26 am
go see this ... http://www.airspayce.com/mikem/arduino/AccelStepper/ (http://www.airspayce.com/mikem/arduino/AccelStepper/)
Title: Re: PWM frequency library
Post by: saptarshi007 on Jan 10, 2015, 09:00 pm
I used PWM library to generate PWM signals of desired frequency. The problem is i am not able to give a phase shift to the PWM. For example i am generating a PWM of frequency of 25Khz on PIN 9 and i need a phase shift of 90 degrees(i.e a phase shift of 40 microseconds) of the same PWM on PIN10. 'delay' command is not working. Please suggest a solution and thank you.   
Title: Re: PWM frequency library
Post by: ewholz on Feb 03, 2015, 10:30 pm
Thanks for this library!
Title: Re: PWM frequency library
Post by: luxornet on Feb 16, 2015, 06:45 pm
Thank you runnerup (http://arduino.cc/forum/index.php?action=profile;u=38942) for this nice piece of work!

I have some questions for you, since I really need to expand this library for the Micro/Leonardo.
So that is what I will do, but maybe you can help me in the right direction.

  • In your estimation, can I better build of of ATimerDefs or BTimerDefs?
  • Do you have any idea how I could implement the difference in structure of the new 8 - 10 - 16 bit pins and fast PWM?
  • I want to change some of the timer--pin assignments for my project. Is that something that you think will work correctly with the construction you used for the library?
  • I will find my way in the end, but can you give me some places to start looking for the registers and stuff?


Any hint is welcome.

Many thanks in advance!
Christophe aka Petit Jean
Any luck with Arduino Leonardo?
Thank you
Title: Re: PWM frequency library
Post by: CrossRoads on Feb 19, 2015, 07:02 pm
@Talhaamjad,
Please don't crosspost.  I see this same request in Project Guidance. Duplicate is being deleted.
Moderator.
Title: Re: PWM frequency library
Post by: wcbagley on Feb 20, 2015, 01:15 am
Anyone have any ideas how to get this library to work with the 1.6.0 version of the IDE? I am having trouble getting it to recognize the library if it is in the "libraries" directory. I tried moving the files to a src directory but that did not help.

I finally gave up and put the files into the same directory as my sketch. That way I can get it to compile, but the output pin no longer has any output.

For reference, this sketch worked in the older version if the IDE. The sketch only stopped working when I upgrade to 1.6.0.
Title: Re: PWM frequency library
Post by: lestofante on Feb 20, 2015, 12:08 pm
i think is the new library system, it need to be updated
Title: Re: PWM frequency library
Post by: z7852424120 on Mar 03, 2015, 10:29 am
I want six pins pwm output.
I use your library.
The pin6 and pin11 always duty=100%.
Why they didn`t work correctly like other pin?
Here is my code,please give me an answer,thanks.


#include <PWM.h>
void setup()
{
     InitTimers();
     Serial.begin(115200);
     Serial.println();
 
   
     Timer0_SetFrequency(400000);
     Timer0_SetPrescaler(ps_8);
     
     Timer1_SetFrequency(50000);
   
     Timer2_SetFrequency(400000);
     Timer2_SetPrescaler(psalt_8);

     


}

void loop()
{
   int x=32768;
   pwmWrite(5,128);//timer0
   pwmWrite(6,128);
   
   pwmWriteHR(9,x);//timer1
   pwmWriteHR(10,x);
   
   pwmWrite(3,128);//timer2
   pwmWrite(11,128);
   Serial.println("High Resolution PWM");
}
Title: Re: PWM frequency library
Post by: adio7292 on Mar 29, 2015, 10:12 pm
I am trying to get the library to work and am very new to programming. I am receiving these errors. Does anyone know how to remedy these problems?

1)Arduino\libraries\PWM/ATimerDefs.h:179:3 error: #error "ATimerDefs.h only supports ATMega640, ATMega1280, ATMega1281, ATMega2560, and ATMega2561"

2)Arduino\libraries\PWM/PWM.h:36:33: error: utility/BTimerDefs.h: No such file or directory

3)Arduino\libraries\PWM/BTimerDefs.h:56: error: 'uint16_t' does not name a type

4)Arduino\libraries\PWM/BTimerDefs.h:57: error: 'uint16_t' does not name a type

Much appreciated!
Title: Re: PWM frequency library
Post by: jim_beam on Apr 02, 2015, 11:53 pm
Thank you for the great library!

I have a beginner question, how do I invert one of the outputs e.g. on Timer1 (Pin12 non-invertet, and pinPin11 inverted) on a MEGA.

And 2nd, how do I add an lokking so that Pin 12 and 11 never be HIGH at the same time.

So far I was playing with code from, with limited Frequenzy up to 32kHz:
https://www.youtube.com/watch?v=D826h-YQun4&feature=youtu.be (https://www.youtube.com/watch?v=D826h-YQun4&feature=youtu.be)

My Code so far:
Code: [Select]
/*  
Phase correct inverted 2CH (HS and LS) PWM, 32kHz, 0-255 DutyCycle

http://playground.arduino.cc/Main/TimerPWMCheatsheet
https://www.youtube.com/watch?v=D826h-YQun4&feature=youtu.be
http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM

lock   ns Verriegelung
-----------------
1       34        
2       95
3      162
4      225
5      284
6      342
7      411
8      470
9      535
10     600
20    1220
30    1840

FRQ: 32,377kHz

Mega:
Timer 0 - Pin 13,4  - 64kHz - NO lock! - millis()!
Timer 1 - Pin 12,11 - 32kHz
Timer 2 - Pin 10(HighSide) ,9(LowSide) - 32kHz
Timer 3 - Pin 5,3,2 - ?
Timer 4 - Pin 8,7,6 - ?

x = % / 2.55;
% = x * 2.55

*/


//--- Global Variables ---------------------
byte x = 0;                     // Aussteuerung 0-255 (0 LS OFF; 1 HS ON
const byte lock = 10;           // Verriegelung (s.o.)
int delta = -1;                 // Duty Cycle verschieben


//--- FCN Declarations ----------------------
void setInvPWM(byte x=127, byte lock=10);  


//--- Setup ---------------------------------
void setup() {  
TCCR2A = TCCR2A | 0x30;         // Set Timer 2 inverted
TCCR2B = TCCR2B & 0xF8 | 0x01;  // Set Timer 2 Prescaler FRQ
//Serial.begin(115200);         // Debug
}


//--- Main loop -----------------------------
void loop() {  

  setInvPWM(x,lock);            // Set Inverted HalfBridge PWM and lock on Mega Timer2
    
  if(x==255 || x==0){
    delay(2000);                // extra Pause
    delta = -delta;
  }  
  
  x +=delta;;                   // Tastverhältniss durchzaehlen, autorollover
  
  delay(50);
}


//--- set Inverted PWM Chanels -------------
void setInvPWM(byte x, byte lock){
  int y;                        // Helper for LS
  
  if(x<1) y = 255;              // Set LS to 0
  else if(x>(254-lock)) y = 0;  // Set LS to 1
  else y = x+lock;              // Verrieglung
  
  if(y<0) y=0;                  // limt to 0
  else if(y>255) y=255;         // limt to 255
  
  // Timer 2 on Mega Pins: 10,9
  analogWrite (10, (x));        // write PWM HS
  analogWrite (9, (y));         // write PWM LS
}


And thats what I want it to look like, but with higer frequency:
(http://www11.pic-upload.de/thumb/02.04.15/ci5hydjgphr.png) (http://www.pic-upload.de/view-26600630/dq2.png.html)

What do I need to do if I use this nice lib?
Thanks a lot!

Title: Re: PWM frequency library
Post by: nadeemqandeel on Apr 04, 2015, 12:15 am
I got a question, I used your library to generate PWM signals on my arduino uno. I used the code you had written but added to it pin3, pin11 and pin10 along with pin9. so that all of them would generate a PWM signal of frequency 108KHz. Now the problem is that pin 11 can not generate that PWM signal while the rest of the pins can. I don't know why. I thought that pin 11 is broken but I tried another code on it to light an LED and it worked fine. I attached the code below. Thank you very much for your help and for posting that library.

#include <PWM.h>

//use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
int led = 9;                // the pin that the LED is attached to
int led2 = 10;              //added
int led3 = 11;              //added
int led4 = 3;              //added
int brightness = 0;         // how bright the LED is
int fadeAmount = 5;         // how many points to fade the LED by
int32_t frequency = 108000; //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);
  bool success2 = SetPinFrequencySafe(led2, frequency); //added
  bool success3 = SetPinFrequencySafe(led3, frequency); //added
  bool success4 = SetPinFrequencySafe(led4, frequency); //added
  //if the pin frequency was set successfully, turn pin 13 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);
 
pwmWrite(led2, brightness);

  brightness = brightness + fadeAmount;

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

pwmWrite(led3, brightness);

  brightness = brightness + fadeAmount;

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

  brightness = brightness + fadeAmount;

  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;   
 }     
 
  delay(30);   
}
Title: Re: PWM frequency library
Post by: nadeemqandeel on Apr 04, 2015, 12:48 am
Hi, I am having the same problem as you did. I need all 4 pins and pin 11 is not giving me an output on oscilliscop! did you figure it out, please let me know if you did. Thank you very much.
Title: Re: PWM frequency library
Post by: RichMo on May 29, 2015, 03:09 am
I made a 1Hz to 2MHz Adjustable frequency PWM library for Arduino. Maybe this will help you.
http://www.rmcybernetics.com/projects/code/index.htm
Title: Re: PWM frequency library--cannot get PWM output on pin 46 Mega R3
Post by: alamocreek on Jun 06, 2015, 08:25 pm
Using Arduino Mega R3.

PWM Library v05 (latest I can find)

Example runs perfectly on pin 11, checked frequency and duty cycle with scope at 20KHz PWM freq.

Change example code to pin 46 as follows (this is the only change)

int led = 46;                // the pin that the LED is attached to

Code loads, pin 13 goes high but no PWM output, I only see pin 46 slowly (every second or two) toggle between low and high.

What did I do wrong?

best

Albert
Title: Re: PWM frequency library
Post by: Dirk67 on Jun 10, 2015, 06:33 pm
Any luck with Arduino Leonardo?
Thank you
For leonardo I found this article: --> http://r6500.blogspot.de/2014/12/fast-pwm-on-arduino-leonardo.html (http://r6500.blogspot.de/2014/12/fast-pwm-on-arduino-leonardo.html)
not a ready to use library,
but really good explained how to do...
Title: Re: PWM frequency library
Post by: Isaac96 on Jun 12, 2015, 03:10 am
The Google Code page seems to have been orphaned.
Title: Re: PWM frequency library
Post by: roeebloch on Jun 18, 2015, 06:04 pm
You can see some PWM driving high power motors at
www.electronics-freak.com (http://www.electronics-freak.com)
Roee
Title: Re: PWM frequency library
Post by: svacker on Jul 30, 2015, 09:37 am
Hi guys,

Let me first introduce my project: I'm making a pilot box (with RFID, LCD and interlock (based on a H-bridge) which basically controls the charging proces of an Electric Vehicle.

Everthing is working well except one thing: I'm using the frequency/ PWM library to generate a DC or PWM signal. With this signal the EV can see if he is ready to charge (9V PWM) or not (12V DC) or the vehicle is charging (6V PWM). Pin 10 of the arduino MEGA is translated from +5/0 to +12/-12. I'm using an opamp to get the 12V and -12V signal (see attachment). the -input is used for the divider and the + input for the PWM. It has to generate a 12V DC , a 9V PWM or a 6V PWM signal with a 1kHz frequency. But i'm having some problems with that. I'm getting a 12V DC , 9V DC and 6V DC signal so pin 10 won't generate a pwm signal (see attachment, constant 4V DC).
I'm using pwmWrite to generate different duty cycles for different current's.

My code (very straightforward):

Code:

Code: [Select]


#include <PWM.h> //We include the library for //changing the frequency of the PWM signal
//http://forum.arduino.cc/index.php?topic=117425.0


int32_t frequency=1000; //We set the frequency of the PWM at 1000 Hz




//Declare all variables in head section

float Vpilot=0;


const int sensorPin = A1;
int sensorValue = 0; //This wil measure the input voltage with a number between 0 annd 1023
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value


int PWMsignal=0; //Variable for knowing if the EV supply equipment produces a PWM signal or not
int Ipp=0; //We create a variable to indicate the maximum current that can flows in the cable. If any of the resistors below is connected, then the maximum current will always be 0 A (No current)

int Pin=10; //Generates the PWM with a 1000Hz frequency
int Ivp=32; //We assign the current limit set for the equipment in A (a maximum of 32A with the switch)

int PP=A6; //Pin attached before the resistor of the proximity
int I=0; //Variable that contains the real current that will flow


int VolPP; //Variable to store the voltage before the resistor of the proximity (It is a number between 0 and 1023)
float VPP;
float v2;

//Duty Cycle
float DC; //The duty cycle for PWM
int DCint; //The duty cycle for the output pin



boolean stateA=true;
boolean stateB=false;
boolean stateC=false;
boolean del = false;
int Mos=13; //Pin for Mosfet (Contacto)r
int prox;

//The setup routine runs once when you press reset:

//-----------------------------------------------------
void setup() {
 
 
 Serial.begin(9600); //Initialize serial communication at 9600 bits per second
   InitTimersSafe();
   bool success=SetPinFrequencySafe(10,frequency);

 

}

//The loop routine runs over and over again forever:
void loop() {
 
pinMode (PP, INPUT);
VolPP=analogRead(A6); //Variable to store the voltage before the resistor of the proximity (It is a number between 0 and 1023)
v2=VolPP*5;
VPP=v2/1023; //We transform the voltage from 0- 1023 to 0-5V and we storage it in the variable VPP
 prox=0;
//We check the voltage before the resistor of the proximity and depending on it we can know how much is the resistor and assign the maximum current

if (VPP>2.9 && VPP<3.15){ //The resistor of the proximity is around 1500Ω
prox=1500;
}
if (VPP>1.80 && VPP<2.18){ //The resistor of the proximity is around 680Ω
prox=680;
}
if (VPP>0.85 && VPP<1){ //The resistor of the proximity is around 220Ω
prox=220;
}
if (VPP>0.42 && VPP<0.51){ //The resistor of the proximity is around 100Ω
prox=100;
}
Serial.print("VPP:");
Serial.println(VPP);
//We check the voltage before the resistor of the proximity and depending on it we can know how much is the resistor and assign the maximum current

switch (prox){
 case 1500: //The resistor of the proximity is around 1500Ω
 Ipp=13;
 break;
 case 680: //The resistor of the proximity is around 680 Ω
 Ipp=20;
 break;
 case 220: //The resistor of the proximity is around 220Ω

 Ipp=32;
 break;
 case 100: //The resistor of the proximity is around 100Ω

 Ipp=63;
 break;
 
 default:
 Ipp=0;
 }
 I=min(Ipp,Ivp);
 Serial.println("Proximity:");
 Serial.print(prox);
 Serial.println(" - "),
 Serial.println(I);
 //lcd.print(I);
 //----------------------------------------------------------------------------------------------------------------------------
 
//We make 12 measurements of the voltage (1.2ms) to make sure in case we have a PWM signal which one is the highest and the lowest voltage:
//int sensorValue = A1;

for (int i=0; i<100; i++){
 
 sensorValue = analogRead(sensorPin); //Read the input on pin A1 (0-1023)
 Vpilot=((sensorValue-512)*24/1023);
 delay(150);
 //Vpilot is now between -12 and +12
 
 if (sensorValue > sensorMax) {
     sensorMax = sensorValue;
   }

   // record the minimum sensor value
   if (sensorValue < sensorMin) {
     sensorMin = sensorValue;
 }
 }
 //Note: 5V corresponds to a range of -12 to +12

 Serial.print("sensorvalue:");
 Serial.println(sensorValue);
 pinMode(Mos, OUTPUT);
 //We determine if there is or not a PWM signal:
   if (sensorValue>=930){
   stateB=false;
   stateC=false;
   stateA=true;
   digitalWrite(Mos, LOW);
   PWMsignal=0; //State A, no pilot
   }
   if (sensorValue>=650 && sensorValue<=730){
   stateB=true;
   stateC=false;
   stateA=false;
   digitalWrite(Mos, LOW);
   PWMsignal=1; //If the pilot´s voltage  isaround 9V, it means we are in state B1  and we create a PWM signal to go t   state B2
   }
   else if(sensorValue<480 && I > 0)
   {
   stateC=true;
   stateB=false;
   stateA=false;
   digitalWrite(Mos, HIGH);
   PWMsignal=1; //If the pilot´s voltage is around 6V, it means we are in state C1 and we create a PWM signal to go to  state C2
   }

//---------------------------------------------------------------------------

   Serial.print("PWMsignal:");
   Serial.println(PWMsignal);
   pinMode(Pin, OUTPUT);
   if (PWMsignal == 0) { //When there is current onthe Pin 9 and there is not a PWM signal,then the pilot´s voltage is 12 V
     
       digitalWrite(10, LOW);
   }
   //
  // float DC = 0.0;
  if (PWMsignal == 1) { //When there is a PWM signal on the pin 9, then the pilot´s voltage is a PWM signal between 12V and - 12V
     // We create the PWM signal in the PIN 9 between 12V and -12V

     if((I>=6) && (I<=51))
     {
     DC = (I / 0.6) / 100;
     }
     //85% < duty cycle <= 96%
     else if (I > 51 && I <= 80) {

       DC = ((I / 2.5) + 64) / 100;
       
     }
     
     else if (I == 80)
     {
       DC = 96;
       //10% <= duty cycle <= 85%
     }
   //  /100  >> percentage
   //float DC = 0.0;
   DCint = DC * 255;
   
   //As Analog output pin is 8bit we can get maximum 2^8=256 or a range of values between 0 to 255.
   
   //Sending the value 255, to the LED input produces 100% duty-cycle, which results in full power on a PWM pin.
   //Sending the minimum value 0, to the LED input produces 0% duty-cycle, which results in no power on a PWM pin.

   //Next line disabled for testing


   pwmWrite(Pin, DCint); //We create the PWM signal in the Pin 9 with a duty cycle=DCint
   Serial.print("Dutycycle:");
   Serial.print(DCint);
   Serial.print(" - ");
   Serial.println(DC);

  }
}
//------------------------------------

Thanks for the help,

kind regards,

Sepp
Title: Re: PWM frequency library
Post by: Isaac96 on Aug 04, 2015, 03:15 am
#1. Use code tags. It makes it easier to read code.
4V? Seems like your voltage is not being amplified or something.
Title: Re: PWM frequency library
Post by: svacker on Aug 04, 2015, 11:06 pm
I did some tests with the scope today:

Apparently it's just PWM pin 10 that won't generate a PWM signal

I guess I will have to use PWM pin 9 (I'm using already the other pin's) but this one's on the same timer (timer 2 of the Mega) of pin 10 so I'm not sure if this will infuence pin 9. using pin 11 gives another weird result (picture 2).



Sepp
Title: Re: PWM frequency library
Post by: Hafiz_Ahmad on Aug 27, 2015, 01:24 pm
Hello sir,
1st of all thanx for the library and effort. but how can i use all of the pwm pins on mega 2560 beacuse i am making a  3 phase inverter and i require all of them operational and currently i am only getting only 11 and 12 operational. looking for a reply from you. 
Title: Re: PWM frequency library
Post by: lufi on Sep 05, 2015, 12:45 pm
Hi,

with Arduino IDE 1.05 this Library works really nice, but not with IDE 1.6.5.
Any Idea why ?

Title: Re: PWM frequency library
Post by: JcanReefMan on Sep 13, 2015, 05:40 pm
Hi All,

I'm new to the Arduino family and my first project is PWM related. My research has led me to this library but i am unable to install it into IDE1.6 as I get an error that it is not a valid library file. When comparing it to the ones already installed I noticed that the folder didn't include libraray.properties or readme.adoc files. Could this be the problem?

Thanks
Title: Re: PWM frequency library
Post by: JcanReefMan on Sep 26, 2015, 01:57 pm
I managed to get the PWM library working with IDE 1.6 by doing the following:

1. Download and unzip Arduino PWM Frequency Library v-05, here you will find three folders, "PWM", "PWM_lib_example" &     "PWM_lib_resolution_example". Move the the two example folders into the PWM folder.

2. The go to C:\Program Files (x86)\Arduino\libraries and copy the "PWM" folder here.

3. When complete your libraries folder should look like the attached picture.

4. Restart the ide and PWM should now be available in your list of libraries.

Title: Re: PWM frequency library
Post by: RossAWaddell on Oct 18, 2015, 05:20 pm
I managed to get the PWM library working with IDE 1.6 by doing the following:

1. Download and unzip Arduino PWM Frequency Library v-05, here you will find three folders, "PWM", "PWM_lib_example" &     "PWM_lib_resolution_example". Move the the two example folders into the PWM folder.

2. The go to C:\Program Files (x86)\Arduino\libraries and copy the "PWM" folder here.

3. When complete your libraries folder should look like the attached picture.

4. Restart the ide and PWM should now be available in your list of libraries.


Thanks! This was a big help.
Title: Re: PWM frequency library
Post by: JcanReefMan on Oct 23, 2015, 04:08 pm
You're welcome
Title: Re: PWM frequency library
Post by: strager_smz on Oct 28, 2015, 10:10 am
hello,
I am trying to use this library to set frequency for my pins, but this is also presetting some duty cycle as well. I want to change duty cycle through labview interface, It works well normally, but when I set the pin frequency through this library I don't have control over duty cycle. Any help? 
Title: Re: PWM frequency library
Post by: q2dg on Nov 13, 2015, 06:02 pm
There's no github with this library exported? Google Code is closed! Thanks
Title: Re: PWM frequency library
Post by: donperry on Nov 28, 2015, 08:18 pm
Not getting this to work with the NANO. The LED example only turns it on and off, it's acting like a binary 0 and 1, not fading just on and off blinking (255=on,0=off), not pwm'ing.

I was doing something wrong. IT works flawlessly. Just got to be sure of the pins you are using, that they are capable of the frequency you are requesting (8bit limitation on some pins)
Title: Re: PWM frequency library
Post by: sjimmie on Dec 03, 2015, 09:13 am
I made a 1Hz to 2MHz Adjustable frequency PWM library for Arduino. Maybe this will help you.
http://www.rmcybernetics.com/projects/code/index.htm
Hi, I have seen your PWM library.
What I don't fully onderstand is how to use the pulsewidth.
If I have a frequency of 75Hz, what should the pulsewidth be for 50% dutycycle?
75Hz is 13,33 msec, so 50% is 6,67 msec, so pulsewidth should be about 6666667 nsec?
Title: Re: PWM frequency library
Post by: 68tjs on Dec 03, 2015, 09:11 pm
Quote
If I have a frequency of 75Hz, what should the pulsewidth be for 50% dutycycle?
To create a signal with 50/50 duty cycle,  timer in CTC mode is more effective than timer in PWM mode.
Title: Re: PWM frequency library
Post by: lestofante on Dec 03, 2015, 10:02 pm
but yes, calculation are correct. We can assume the width is of the HIGH signal, so a 25/75 duty is ~3200000ns
Title: Re: PWM frequency library
Post by: SimenC on Dec 17, 2015, 10:09 am
Good work runnerup! This library seems very useful!

Quote
I am having difficulties to make it compile in my Arduino 1.6.6 environment. I read the entire thread and searched the Arduino site on library implementation. I have used other libraries before and even written a few of my own, but i cant get this one properly installed. I have the folders and files arranged like this:

../libraries/PWM/examples/PWM_lib_example/PWM_lib_example.ino
../libraries/PWM/examples/PWM_lib_resolution_example/PWM_lib_resolution_example.ino

../libraries/PWM/utility/ATimerDefs.cpp
../libraries/PWM/utility/ATimerDefs.h
../libraries/PWM/utility/BTimerDefs.cpp
../libraries/PWM/utility/BTimerDefs.y

../libraries/PWM/keywords.txt
../libraries/PWM/PWM.h

What am I doing wrong? I'm sure it is right there in front of me and that I should see it, but I don't. Any help is much appreciated.
Never mind this post. My Arduino installation was corrupt. It compiles after I reinstalled the inviroment. Thank you for this awesome library!

Kind regards,
Simen
Title: Re: PWM frequency library
Post by: Mikey3110 on Jan 02, 2016, 12:49 pm
Good morning,

Is it possible, that there is an issue within this library?

I have tried to set the Frequency at PIN 2 form my Mega 2560 at 1kHz.

I have tried to manage this on several ways, by setting the "pinfrequency" and later the "timerfrequency".

I need to set the frequency to 1kHz at 11 Pins. Pin 13 to 11 are working well with this library.
But i have no idea, how to manage the Frequency at the other Pins.

Code: [Select]

#include <PWM.h>


void setup() {
  // put your setup code here, to run once:
InitTimers();
SetPinFrequency(2,500);
pinMode(2,OUTPUT);
}

void loop() {

//pwmWriteHR(testpin,20000);
pwmWrite(2,255);
  // put your main code here, to run repeatedly:

}


Can someone help me?

Here is the code:





Thank you very much!
Title: Re: PWM frequency library
Post by: SimenC on Jan 04, 2016, 01:46 pm
Is it possible, that there is an issue within this library?

I have tried to set the Frequency at PIN 2 form my Mega 2560 at 1kHz.

I have tried to manage this on several ways, by setting the "pinfrequency" and later the "timerfrequency".
But what is going wrong? Have you tried to write 127 instead of 255 for testing?

How did you implement the library? I am having trouble getting it to compile.
Title: Re: PWM frequency library
Post by: kalu1 on Jan 10, 2016, 02:18 am
Hey guys,

I have one quick simple silly question.
I'm thinking about using this library for controlling SSR relay (heating water in coffee maker).
Is there any benefit for using PWM library instead digitalWrite for my purpose?

Thank you and I'm really sorry for this kind of question
Title: Re: PWM frequency library
Post by: rinkrides on Jan 10, 2016, 03:05 pm
kalu1: digitalWrite will work fine for your task. Consult the datasheet of your SSRelay, should list a maximum frequency response of sorts. PWM'ing it may break it. Hope this helps. Usually that type of heater has almost two minutes pulse width. Generally though a Keurig uses a temp sensor to tell when the water is hot enough.
Title: Re: PWM frequency library
Post by: Harshaks on Jan 27, 2016, 07:00 am
#include<PWM.h>
int32_t frequency =100000;
void setup()
{
 InitTimersSafe() ;
bool success = SetPinFrequencySafe(9, frequency);
if(success) {
  pinMode(13, OUTPUT);
  digitalWrite(13,HIGH);
}
}

void loop() {
int sensorValue= analogRead(A0);
pwmWrite(9, sensorValue /4);
delay(30);

}
 i am applying freq of 50hz from signal gen  through a diode at a0 and i am getting pwm for +VE cycle( as i hv used diode),so i need to save this and then send it during -ve cycle in order to get total pwm
anyone could help with the code
Title: Re: PWM frequency library
Post by: benv666 on Mar 03, 2016, 11:32 am
Does anyone know if this library broke on arduino 1.6?

I've used this library for outputting 4 PWM signals for my custom aquarium LEDs, it worked fine for over a year.
(running on an arduino mega2560 with a WizNet 5500 ethernet board on top)
Now I wanted to make some changes, recompiled the code using the latest arduino libraries on Arch linux and it simply doesn't work anymore. No errors, but only pin 11 seems to work (but not properly), pins 5 / 6 and 44 simply give no signal as far as I can tell.
Using analogWrite instead of pwmWriteHR turns on the LEDs without problems.

Does anyone have any clue as to what the cause might be?

Wouter
Title: Re: PWM frequency library
Post by: gicking on Mar 22, 2016, 09:24 pm
hello all,

I plan to use an Arduino Uno as a PWM generator for testing external electronics at work --> need optimum signal quality. Therefore I have measured the PWM accuracy for both TIM2 (8-bit) and TIM1 (16-bit). Attached please find the results for frequency and duty cycle errors. Summary:


Overall a very nice result for the 16-bit timer and a very easy to use library --> thanks a lot for your great work!!  :)

Just a few comments on the 8-bit timer:


Thanks again for your great library. Hope I could return something by the attached measurements.

Greetings from Germany,
Georg
Title: Re: PWM frequency library
Post by: atmelino on Mar 25, 2016, 01:04 am
Does anyone know if this library broke on arduino 1.6?

I've used this library for outputting 4 PWM signals for my custom aquarium LEDs, it worked fine for over a year.
(running on an arduino mega2560 with a WizNet 5500 ethernet board on top)
Now I wanted to make some changes, recompiled the code using the latest arduino libraries on Arch linux and it simply doesn't work anymore. No errors, but only pin 11 seems to work (but not properly), pins 5 / 6 and 44 simply give no signal as far as I can tell.
Using analogWrite instead of pwmWriteHR turns on the LEDs without problems.

Does anyone have any clue as to what the cause might be?

Wouter
I got it to work following the instructions from post #102:

Download and unzip Arduino PWM Frequency Library v-05, here you will find three folders, "PWM", "PWM_lib_example" &     "PWM_lib_resolution_example". Move the the two example folders into the PWM folder.


Title: Re: PWM frequency library
Post by: Burak93 on Apr 19, 2016, 06:17 pm
Does anyone know if this library broke on arduino 1.6?

I've used this library for outputting 4 PWM signals for my custom aquarium LEDs, it worked fine for over a year.
(running on an arduino mega2560 with a WizNet 5500 ethernet board on top)
Now I wanted to make some changes, recompiled the code using the latest arduino libraries on Arch linux and it simply doesn't work anymore. No errors, but only pin 11 seems to work (but not properly), pins 5 / 6 and 44 simply give no signal as far as I can tell.
Using analogWrite instead of pwmWriteHR turns on the LEDs without problems.

Does anyone have any clue as to what the cause might be?

Wouter
Hello Wouter,
did you solce your problem? i have also the same problem with the library, it only works for pin 11 and 12 but i need one more pwm output. I wrote a simple code to test it and measured the output with oscilloscope.


Code:

Code: [Select]
#include <PWM.h>

int led = 11;                // the pin that the LED is attached to

int32_t frequency = 100; //frequency (in Hz)

void setup()
{
 InitTimersSafe();

 //sets the frequency for the specified pin
 bool success = SetPinFrequencySafe(led, frequency);

 if (success) {
   pinMode(13, OUTPUT);
   digitalWrite(13, HIGH);
 }
 pwmWrite(led, 0);
 delay(2);
 SetPinFrequencySafe(led, frequency);
 pwmWrite(led, 127);

}

void loop()
{

}
Title: Re: PWM frequency library
Post by: raschemmel on Apr 22, 2016, 03:02 am
Does anyone know which Reply# in this thread would have a working code example of how to get  a PWM frequency of 10 khz ? All I need is a simple pot => analog input A0 that converts that to duty cycle at 10 khz.
Thanks
I installed the library but not sure how to use it and this thread is really long.

Nevermind. I found one here (https://www.youtube.com/watch?v=9JXGIeM3BSI)

Code: [Select]
  #include <PWM.h>
int32_t frequency = 10000; // frequency (in Hz)
 int sensorValue =0;

void setup()
{
  // put your setup code here, to run once:
  InitTimersSafe();
  bool success = SetPinFrequencySafe(9, frequency);
  if(success) {
    pinMode(13,OUTPUT);
    digitalWrite(13,HIGH);
   }
 }

void loop()
   {
    // put your main code here, to run repeatedly:
    int sensorValue = analogRead(A0);
    pwmWrite(9,sensorValue/4);
    delay(30);
    }
Title: Re: PWM frequency library
Post by: adityan1991 on Apr 27, 2016, 07:56 am
How can I generate 1 MHz signal with this function??

I'm a novice .. Pls Help.
Title: Re: PWM frequency library
Post by: raschemmel on Apr 27, 2016, 03:34 pm
I don't know. Did you try it (try changing the frequency to 1000000?)
Title: Re: PWM frequency library
Post by: 68tjs on Apr 30, 2016, 10:23 am
Do you thinks it is possible to generate a 1MHz PWM signal with a 16 MHz system frequency ?
What is the result of 16 MHz divide by 256 ?

You should have a look on 328p (or 2560) datasheet !
You will found PWM frequency formula.
Title: Re: PWM frequency library
Post by: raschemmel on May 05, 2016, 07:15 am
Quote
Hello everyone. I am very new to Arduino, so please go easy on me if this is stupid question. I have loaded the sketch and it is working flawlessly for me. The only thing i would like to change is being able to very the frequency using a pot. I don't have to generate a specific frequency, I just need a linear signal from 10Hz to 200Hz, that i can also vary to Duty Cycle. I have a couple other questions, but I'll tackle them one at a time. Thank you in advance for a great resource and any help you can offer.
I could tell you if you start your post. I can't tell you here because your question is not relevant to THIS post. This post is the PWM Library and the frequency is set ONE TIME in SETUP, so you can't change it with a pot.

Start your own post. You can't post on Reply#125 of someone else's post to ask a totally different question.  That is called POST HIJACKING . (which is a violation of forum policy)

DELETE YOUR POST BY CLICKING ON THE '"More" link in the lower right and select REMOVE.

If you don't , the Global Moderator will.

Then choose a forum Topic section and start a topic to ask your question.
Title: Re: PWM frequency library
Post by: meninas92 on May 19, 2016, 09:16 pm
Hi i have tried to contact the supporter of the library "runnerup". i have some minor fixes to the library i have created a zip compatible with newer versions of arduino. does anyone knows how to contact runnerup?
Title: Re: PWM frequency library
Post by: raschemmel on May 19, 2016, 09:46 pm
Did you PM him?
Title: Re: PWM frequency library
Post by: junktronix on May 26, 2016, 07:17 am
I'm curious what you fixed.  I've noticed that occasionally the PWM doesn't start immediately.  The PWM output will be high or low for 5-10mS before the pulses start.

Hi i have tried to contact the supporter of the library "runnerup". i have some minor fixes to the library i have created a zip compatible with newer versions of arduino. does anyone knows how to contact runnerup?
Title: Re: PWM frequency library
Post by: vikramrobo on Jun 19, 2016, 04:17 pm
Hello Sir,


I a trying to use below code from PID loop to set the frequency of two different PWM pins (12 from Timer 1 & 44 from timer 5) , but I have seen only Timer1 will work & no PWM observe on Pin 44. can you help me in this

void motor1_set_speed(unsigned int frq)
{


   Timer1_SetFrequency(frq);
   pwmWriteHR(11, 32768); // Keeping duty cycle 50 % always fix , based on motor specf

}

void motor2_set_speed(unsigned int frq)
{

  Timer4_SetFrequency(frq);
  pwmWriteHR(44, 32768); // Keeping duty cycle 50 % always fix , based on motor specf
}
Title: Re: PWM frequency library
Post by: vikramrobo on Jun 19, 2016, 04:24 pm
Hello Sir,

I am trying to use Time1 pin 12 & Timer 5 pin 44 for PWM purpose , and using PID loop I  want to update
Timer 1 & timer 5 frequency every 100 ms, I have observed only one Timer will run at a time, I mean I observed
 In this case either Time1 work or Timer5 , how can get different PWM frequency from Timer 1 & Timer 4 at a same time, please help

void motor1_set_speed(unsigned int frq)
{

   Timer1_SetFrequency(frq);
   pwmWriteHR(12, 32768); // Keeping duty cycle 50 % always fix , based on motor specf

}

void motor2_set_speed(unsigned int frq)
{

  Timer5_SetFrequency(frq);
  pwmWriteHR(44, 32768); // Keeping duty cycle 50 % always fix , based on motor specf
}
Title: Re: PWM frequency library
Post by: husain081 on Jun 27, 2016, 05:13 am
Hi friends,

Here is my sketch for the motor control using specified PWM frequency,

#include <PWM.h>
const int32_t frequency = 25000 ; //frequency (in Hz)
const int pwm = 9 ;  //initializing pin 9 as pwm
const int in_1 = 2 ;
const int in_2 = 3 ;

void setup()
{
  InitTimersSafe();

  bool success = SetPinFrequencySafe(pwm, frequency);

  if(success){
   pinMode (pwm, OUTPUT);
   pinMode (in_1, OUTPUT);
   pinMode (in_2, OUTPUT);
  }
}

void loop()
{
  digitalWrite(in_1,HIGH) ;
  digitalWrite(in_2,LOW) ;
  pwmWrite(pwm,127) ;
  delay(3000) ;

  digitalWrite(in_1,HIGH) ;
  digitalWrite(in_2,HIGH) ;
  delay(200) ;
}


Now, I would like to read the PWM frequency and the duty cycle through serial port.  I'm also thinking, to set the PWM frequency and duty cycle through serial port and reading them back. I would appreciate if somebody could help me on this as I'm very new to this Arduino world.

Thanks in advance,

Cheers,
Husain

Title: Re: PWM frequency library
Post by: raschemmel on Jun 27, 2016, 06:50 am
To the last two posters:

Thíe forum has rules regarding the posting of code .Please follow these rules and "Modify" your posts by highlighting the code and clickinv the CODE TAGS [</>] button ( first on the left)

@Hussain081,
Not sure if I understand you correctly.
You can send any information you want on the serial port and read it back. What difference does it make if it happens to be a frequency value or a duty cycle ? It' the same as sending
any other values.
The place to start is the Serial.Write and Serial.Read() Playground pages.
Both are numbers and everything is ASCII so you are in fact asking how to send ASCII code for numbers. Look up the values on the ASCII code table . You need to send a termination character like a CR as well.
Google : "arduino sending and receiving multi-digit integers - Bald Engineer"
Title: Re: PWM frequency library
Post by: husain081 on Jun 27, 2016, 08:19 am
Oops, sorry I wan't aware of the forum rules. I will follow it in coming posts...

Thanks for your info mate, I will check...
Title: Re: PWM frequency library
Post by: raschemmel on Jun 27, 2016, 02:13 pm
Modify your last post.( the code)
Title: Re: PWM frequency library
Post by: texmit on Jul 25, 2016, 03:08 am
Does anyone know if this library broke on arduino 1.6?

I've used this library for outputting 4 PWM signals for my custom aquarium LEDs, it worked fine for over a year.
(running on an arduino mega2560 with a WizNet 5500 ethernet board on top)
Now I wanted to make some changes, recompiled the code using the latest arduino libraries on Arch linux and it simply doesn't work anymore. No errors, but only pin 11 seems to work (but not properly), pins 5 / 6 and 44 simply give no signal as far as I can tell.
Using analogWrite instead of pwmWriteHR turns on the LEDs without problems.

Does anyone have any clue as to what the cause might be?

Wouter
I have been able to fix this problem. The ATTimerDefs.h file in the PWM library has a TimerData structure and it appears that a new TIMER1C has been added so the wrong timers are being accessed now. To fix this problem, add a row to the timer_to_pwm_data[] array after line 107:
{0, 0, 0, 0, 0}, //TIMER1C

This will shift all the rows after TIMER1 (which is working - pins 11 and 12) down by 1 and then all the pwm pins will work again.
Title: Re: PWM frequency library
Post by: lcw1125 on Aug 20, 2016, 10:45 am
Thanks runnerup for the awesome library.

I've tested the pwmWriteHR on my Uno with different frequencies (10Hz, 10KHz, 1MHz, 10MHz for example). The "resolution reduce when frequency increase" case seems not happening because the resolution is still 16bit no matter what frequency i set.

I connect pin 3 and pin 9 to LED for comparing its light because i don't have an oscillator. I only need 10 bit resolution, with fixed frequency lets say about 50KHz (or any fixed freq). Can anyone help check on my program to find out what i missed, or is there any other way to get adjustable resolution?

Thanks.


#include <PWM.h>

int led = 9;
int VRef = 0;
int32_t AAA = 0;
int32_t TestFreq = 50000;  //change frequency here

void setup() {
InitTimersSafe();
SetPinFrequency (led,TestFreq);
pinMode (3, OUTPUT);
Serial.begin (115200);
}

void loop() {    
VRef = analogRead(A0);
pwmWriteHR (led, AAA);
analogWrite (3, VRef/4);
AAA = AAA + 1;
if (AAA == 65536){
 AAA = 0;
}
Serial.print ("VR: ");
Serial.print (VRef);
Serial.print ("AAA: ");
Serial.println (AAA);
}
Title: Re: PWM frequency library
Post by: bill_lask on Sep 08, 2016, 02:26 am
Awesome library!!!


I have one problem

i have an arduino mega and i run this code
Code: [Select]

/*

Mimics the fade example but with an extra parameter for frequency. It should dim but with a flicker
because the frequency has been set low enough for the human eye to detect. This flicker is easiest to see when
the LED is moving with respect to the eye and when it is between about 20% - 60% brighness. The library
allows for a frequency range from 1Hz - 2MHz on 16 bit timers and 31Hz - 2 MHz on 8 bit timers. When
SetPinFrequency()/SetPinFrequencySafe() is called, a bool is returned which can be tested to verify the
frequency was actually changed.

This example runs on mega and uno.
*/

#include <PWM.h>

//use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
int led = 3;                // 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 = 35; //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, turn pin 13 on
 if(success) {
   pinMode(6, OUTPUT);
   digitalWrite(6, LOW);    
 }
}

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 have set the pin 6 low but did the same with pin 3 with pwm library
can anybody help me to slove my problem?
Title: Re: PWM frequency library
Post by: hanslanda on Sep 14, 2016, 05:52 am
Hey there guys,

First and foremost, thanks for writing this library. I'm still new to the Arduino world but i can already tell this was much needed by the community even by my basic need of it.


I've not even gone through the testing of this code yet because there are some fundamentals i wish to understand about this library first. Once i get the basic understanding i'm looking for, i will test the code in my current project i'm working on.


Let me start with this. I'm attempting to control a PC water cooling pump thats pwm controlled. The pump itself has a molex connector for its 12v and gnd. It also breaks out to a 4 pin connector which contains the PWM signal and Temp out. So all i need to do is tie into the PWM-in on the pump. Temp pin isn't necessary here and you'll read why below.



1) I'm using a TFT LCD shield on an Arduino mega 2560.


2) The TFT shield uses pins D0 to D7 and i would assume changing the clock on any of those would not be a good thing.

ref.

http://elecfreaks.com/store/download/datasheet/shield/TFT_MEGA_V2.0.pdf


3) I'm also currently using D8 for DallasTemp/oneWire on (3) DB18 temp sensors. Again, prefer not to mess with that, but it would not be a big deal to have to move it as i'm still in breadboard mode.




So here's my real question. According to the "timerpwmcheatsheet" my mega has 5 timers?

timer 0 (controls pin 13, 4)
timer 1 (controls pin 12, 11)
timer 2 (controls pin 10, 9)
timer 3 (controls pin 5, 3, 2)
timer 4 (controls pin 8, 7, 6)



Okay, simple for me. I want to tie into pin 9. If i'm still following here that means i'm going to change timer 2 which should only affect pins 9, 10... neither of which i'm using now. If i'm not lost and this is the case... i can't help but stumble on the way this library describes its global functions. See below


Code: [Select]


InitTimers() Initializes all timers. Needs to be called before changing the timers frequency or setting the duty on a pin

//Okay no problem.


InitTimersSafe() Same as InitTimers() except timer 0 is not initialized in order to preserve time keeping functions

//This. If you are not changing timer 0, why would this be important? Or are you 'changing' timer 0 JUST by initializing it?


SetPinFrequencySafe(int8_t pin, int32_t frequency) Same as SetPinFrequency except it does not affect timer 0

//I have the exact same question here. If i change the frequency of pins on timer 2, it wouldn't affect timer 0... so why would i need this?




Next:


Code: [Select]


Timer1_GetFrequency() Gets the timer's frequency in Hz
//Simple enough


Timer1_SetFrequency(int frequency) Sets the timer's frequency in Hz
//Wonderfully simple


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)
//I read a limited amount on this, but from my limited need, i shouldn't need to use this.


Timer1_SetPrescaler(enum value) Sets the prescaler*
//Same as above


Timer1_GetTop() Gets the timer register's maximum value
//Debug function more or less?


Timer1_SetTop(int top) Sets the timer register's maximum value
//I'm not sure how to use this. I thought timers already had fixed maximum values.


Timer1_Initialize() Initializes the timer
//A way to initialize a single timer? Seems ideal for me since i'm only interested in changing one?





Please correct me on my lack of understanding where it exists. The goal is simply to get this pump to run 100% speed. Since currently it appears to be running at its slowest possible speed. I also read motherboard PWM outputs run at 25kHz. So i simply want to change pin 9 to 25kHz with 100% duty cycle. I assume this will accomplish my needs. Again correct me if i'm wrong lol.



So i guess by my rudimentary understanding, here is what ill add for code.



In setup:


Code: [Select]


Timer2_Initialize()

Timer2_SetFrequency(25000)

pwmWrite(9, 255)





Otherwise i guess i could do this?



Code: [Select]


InitTimersSafe()

SetPinFrequencySafe(9, 25000)

pwmWrite(9, 255)




Again my main concern is that initializing the timers does something to the timer i guess i'm not understanding, which is why you require this safe function? My real fear, given the previous sentence is a reality, and i am affecting other timers, then my concern is that could affect pwm pins 0-7, which are used by my LCD shield.


Any comments greatly appreciated. If i should post this elsewhere please let me know.



*update*

I tested both code segments i posted above as examples. Either i have the quietest pump on the planet, which Also was already running at full speed, or it didn't change anything in my situation.
Title: Re: PWM frequency library
Post by: raschemmel on Sep 14, 2016, 03:02 pm
Use CODE TAGS [</>] button for code.
Title: Re: PWM frequency library
Post by: hanslanda on Sep 14, 2016, 03:17 pm
Use CODE TAGS [</>] button for code.
I barely posted any code at all. But i added the code tags for your viewing pleasure.
Title: Re: PWM frequency library
Post by: raschemmel on Sep 14, 2016, 03:40 pm
Thanks. It helps make the code stand out from everything else. (among other things, like scrolling)
Title: Re: PWM frequency library
Post by: hanslanda on Sep 14, 2016, 04:36 pm
Thanks. It helps make the code stand out from everything else. (among other things, like scrolling)
I keep failing on adding the code tags :P


Do you see anything i could be doing wrong off the bat with my above description? Using the two code segments at the bottom of my post, i was unable to see any difference in motor speed. I do need to test this on a fan or another device to make sure the pump isn't giving me grief, but until i can do that.. i would just like to know my code is correct. For reference changing the pin timers i changed did not interfere with my touch screen/lcd.
Title: Re: PWM frequency library
Post by: naeemawan36 on Sep 27, 2016, 07:52 pm
i m unable to add library plz tell me how to add pwm library cuz software say folder dosenot contain valid library
Title: Re: PWM frequency library
Post by: mexus on Oct 06, 2016, 11:21 am
I have a problem with the library (latest version v_05).
Arduino Mini Pro - IDE 1.6.10.

If Init all timers (safe or not) I lose pwm outputs on timer 0 and 2 (pins 5,6,3,11).
If I Init only timer1, I can use the other two timers.

Not working code (no PWM on pin 11):
Code: [Select]
#include <PWM.h>
void setup() {
    Timer1_Initialize();
    Timer2_Initialize();
    Timer1_SetFrequency(3921);
    Timer2_SetFrequency(3921);
    Serial.begin(9600);
    Serial.println(Timer1_GetTop());
    Serial.println(Timer2_GetTop());
    delay(5000);
}
long x =0;
void loop() {
  pwmWriteHR(9, x);
  pwmWrite(11, 100);
  x+=10;
  if(x>65535)x=0;
  Serial.println(String(x));
}


Working code:
Code: [Select]
#include <PWM.h>
void setup() {
    Timer1_Initialize();
    Timer2_Initialize();
    Timer1_SetFrequency(3921);
    Timer2_SetFrequency(3921);
    Serial.begin(9600);
    Serial.println(Timer1_GetTop());
    delay(5000);
}
long x =0;
void loop() {
  pwmWriteHR(9, x);
  pwmWrite(11, 100);
  x+=10;
  if(x>65535)x=0;
  Serial.println(String(x));
}
Title: Re: PWM frequency library
Post by: leotakacs on Oct 31, 2016, 05:26 pm
I'm having some issues installing this library... Which folder/subfolder do I drop in the libraries folder?

EDIT: Scrath That. I tried it using the Sketch/Import Library option and it worked, but now I'm getting the following error:

PWM_lib_example.cpp.o: In function `loop':
C:\Users\User\Downloads\arduino-1.0.6-windows\arduino-1.0.6/PWM_lib_example.ino:39: undefined reference to `pwmWrite(unsigned char, unsigned char)'
PWM_lib_example.cpp.o: In function `setup':
C:\Users\User\Downloads\arduino-1.0.6-windows\arduino-1.0.6/PWM_lib_example.ino:24: undefined reference to `InitTimersSafe()'
C:\Users\User\Downloads\arduino-1.0.6-windows\arduino-1.0.6/PWM_lib_example.ino:27: undefined reference to `SetPinFrequencySafe(signed char, unsigned long)'
Title: Re: PWM frequency library
Post by: rajanchalotra23 on Nov 06, 2016, 08:21 pm
how to download and install this library, my IDE is showing error.
Arduino: 1.6.11 (Windows 7), Board: "Arduino/Genuino Uno"

Specified folder/zip file does not contain a valid library
I
Title: Re: PWM frequency library
Post by: mysticfree on Dec 08, 2016, 02:27 pm
Like a few others, I'm unable to add this library to my IDE.  Using the "Zip library" menu option, I get the error:

"The library "Arduino PWM Frequency Library v_05" cannot be used.
Library names must contain only basic letters and numbers.
(ASCII only and no spaces, and it cannot start with a number)
Specified folder/zip file does not contain a valid library"

Is there any way to get this library into my Arduino libraries?

Thank you for your help.

Title: Re: PWM frequency library
Post by: mysticfree on Dec 08, 2016, 05:03 pm
ok, figure it out. I had to unzip the "PWM" directory into the Arduino's library directory (..\Arduino\libraries) as "PWM", then unzip the example directories as subdirectories of "\PWM".

Hope this helps.
Title: Re: PWM frequency library
Post by: elser2 on Dec 13, 2016, 04:58 am
Thanks for making the library runner-up. I have a question (i am new to arduino's). What would the code look like to set the frequency on multiple pins? I am building a hydraulic controller and using some I/O on a Mega 2560 to provide PWM for some proportional solenoid valves that require 200HZ. My current problem, is that i am not getting 200Hz on all the pins in the code below, some are putting out 500HZ.

Code: [Select]

#include <PWM.h>
int32_t frequency = 200; //output frequency in Hz

void setup ()
{
 

 
InitTimersSafe ();  //change timer frequency except timer 0
bool success = SetPinFrequencySafe((6,3,5,2), frequency); //pin & Hz

if (success) // if frequency set successful do this loop
{
pinMode (13, OUTPUT); //set pin 13 as a output
digitalWrite(13, HIGH); //set pin 13 high
}
}

void loop ()

     {
             int sensorValue = analogRead (A1); //read analog voltage on pin 0
             pwmWrite(2, sensorValue / 4);// write to pin 9 (divide sensorvalue by 4 to change sensor value scale from 0-1023 to 0-255
             delay(30) ;

             int sensorValue1 = analogRead (A3); //read analog voltage on pin 0
             pwmWrite(3, sensorValue1 / 4);// write to pin 9 (divide sensorvalue by 4 to change sensor value scale from 0-1023 to 0-255
             delay(30) ;

             int sensorValue2 = analogRead (A5); //read analog voltage on pin 0
             pwmWrite(5, sensorValue2 / 4);// write to pin 9 (divide sensorvalue by 4 to change sensor value scale from 0-1023 to 0-255
             delay(30) ;

             int sensorValue3 = analogRead (A7); //read analog voltage on pin 0
             pwmWrite(6, sensorValue3 / 4);// write to pin 9 (divide sensorvalue by 4 to change sensor value scale from 0-1023 to 0-255
             delay(30) ;
     }
Title: Re: PWM frequency library
Post by: randumbhero on Feb 06, 2017, 10:58 pm
Does anyone know of a similar library that works with ATTINY45/85?  Anybody want to help me port this one over?
Title: Re: PWM frequency library
Post by: yatin on Mar 03, 2017, 11:25 am
can we change mode of PWM to fast instead of phase corrected?( as we can get double resolution in fast mode)
Title: Re: PWM frequency library
Post by: DrJones on Mar 16, 2017, 04:17 pm
Having issues using this library, probably some annoying oversight but if anyone could help me get it to run it'd be great. Seems like the compiler is not getting the functions properly somehow..

Code: [Select]
void setup() {
#include <C:\Users\Jonas\Documents\Arduino\Fancontrol\PWM\PWM.h>

InitTimersSafe();
SetPinFrequency(1, 25000);

}

void loop() {

}


Error message:
Quote
C:\Users\Jonas\AppData\Local\Temp\ccWpBMvO.ltrans0.ltrans.o: In function `setup':

C:\Users\Jonas\Documents\Arduino\Fancontrol\main/main.ino:4: undefined reference to `InitTimersSafe()'

C:\Users\Jonas\Documents\Arduino\Fancontrol\main/main.ino:5: undefined reference to `SetPinFrequency(signed char, unsigned long)'

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.
Title: Re: PWM frequency library
Post by: Lior_K on Mar 19, 2017, 02:43 pm
Hi,

I have problem to use this library. I'm using Arduino 1.8.1
I copy the PWM folder to the correct location as mentioned above
In the Library manager i get the following note: "PWM Version unknown INSTALLED"
What i did wrong?

Thx,
Lior

Title: Re: PWM frequency library
Post by: pert on Mar 19, 2017, 06:05 pm
Hi,

I have problem to use this library. I'm using Arduino 1.8.1
I copy the PWM folder to the correct location as mentioned above
In the Library manager i get the following note: "PWM Version unknown INSTALLED"
What i did wrong?

Thx,
Lior


I don't think your error has anything to do with this library. The "PWM Version unknown INSTALLED" entry you see in Library Manager just means you have the PWM library installed and it doesn't define the version. That doesn't indicate any problem and is exactly what would be expected after you install the library. The true error you are encountering is shown in the red text on the black console window at the bottom of the Arduino IDE window. I don't think that has anything to do with the PWM library. I just installed it and opened Library Manager in Arduino IDE 1.8.1 and didn't encounter that error.

When you encounter error messages you should always post them on the forum as text, using code tags (</> button on the toolbar). screenshots are almost never useful and will make it much less likely for you to get help here.
Title: Re: PWM frequency library
Post by: Lior_K on Mar 20, 2017, 01:57 pm
Hi,

Thanks for your reply. Sorry, I'm new Arduino user (-:
I assumed that it's the PWM library since the PWM function are not working while running the program
Could it be connect to the Java version on my PC?

The message that i get is:
Code: [Select]
[/
http://downloads.arduino.cc/packages/package_index.json file signature verification failed. File ignored.
java.lang.NullPointerException
java.lang.RuntimeException: java.lang.NullPointerException
at cc.arduino.contributions.libraries.ui.LibraryManagerUI.lambda$onUpdatePressed$0(LibraryManagerUI.java:212)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:114)
at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:106)
at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:665)
at processing.app.Base.onBoardOrPortChange(Base.java:1295)
at processing.app.Base$12.actionPerformed(Base.java:1522)
at processing.app.Base.filterVisibilityOfSubsequentBoardMenus(Base.java:1561)
at processing.app.Base.access$000(Base.java:82)
at processing.app.Base$11.actionPerformed(Base.java:1494)
at processing.app.Base.rebuildBoardsMenu(Base.java:1472)
at processing.app.Base$8.onIndexesUpdated(Base.java:1327)
at cc.arduino.contributions.libraries.ui.LibraryManagerUI.lambda$onUpdatePressed$0(LibraryManagerUI.java:210)
... 1 more
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:114)
at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:106)
at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:665)
at processing.app.Base.onBoardOrPortChange(Base.java:1295)
at processing.app.Base.openLibraryManager(Base.java:1346)
at processing.app.Base.lambda$rebuildImportMenu$2(Base.java:1060)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
]

Thanks,
Lior
Title: Re: PWM frequency library
Post by: pert on Mar 20, 2017, 02:19 pm
Thanks, that's much better to be able to read the full error output in text. That is quite strange. I don't think it's related to your Java version but I'm not sure of the cause. Do you get that error only when you do Sketch > Include library > Manage libraries or do you also get it when you're trying to compile or upload your sketch?
Title: Re: PWM frequency library
Post by: Lior_K on Mar 20, 2017, 04:04 pm
Hi,

it was while Sketch > Include library > Manage libraries.
the message that i got while compiling is too long to be send here but part of it is:

Code: [Select]
[/avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM9
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega2560
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Wiring
         Description     : Wiring
         Programmer Model: AVRISP
         Hardware Version: 15
         Firmware Version Master : 2.10
         Vtarget         : 0.0 V
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e9801 (probably m2560)
avrdude: reading input file "C:\Users\KAYKOV~1.AUT\AppData\Local\Temp\arduino_build_56302/Testing_the_motor_driver_Using_Timer1_for_Generate_CLK.ino.hex"
avrdude: writing flash (4662 bytes):

Writing | ################################################## | 100% 0.78s

avrdude: 4662 bytes of flash written
avrdude: verifying flash memory against C:\Users\KAYKOV~1.AUT\AppData\Local\Temp\arduino_build_56302/Testing_the_motor_driver_Using_Timer1_for_Generate_CLK.ino.hex:
avrdude: load data flash data from input file C:\Users\KAYKOV~1.AUT\AppData\Local\Temp\arduino_build_56302/Testing_the_motor_driver_Using_Timer1_for_Generate_CLK.ino.hex:
avrdude: input file C:\Users\KAYKOV~1.AUT\AppData\Local\Temp\arduino_build_56302/Testing_the_motor_driver_Using_Timer1_for_Generate_CLK.ino.hex contains 4662 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.62s

avrdude: verifying ...
avrdude: 4662 bytes of flash verified

avrdude done.  Thank you.

http://downloads.arduino.cc/packages/package_index.json file signature verification failed. File ignored.]
Title: Re: PWM frequency library
Post by: pert on Mar 20, 2017, 10:22 pm
The output shows that the sketch has successfully compiled and uploaded. The error you're seeing:
Code: [Select]
http://downloads.arduino.cc/packages/package_index.json file signature verification failed. File ignored.]
will not cause any problems for compiling or uploading the sketch. If the code isn't working correctly that has nothing to do with that error. That error does indicate a problem with Boards Manager and possibly Library Manager this may cause you to be unable to use those features to get updatable boards/libraries notifications or install boards/libraries. Often it's possible to do those processes manually if needed so you may be able to just ignore that. I suspect it's some sort of a network issue. It's trying to verify the downloaded package index file and the verification is failing.
Title: Re: PWM frequency library
Post by: ghost0007 on Apr 06, 2017, 10:40 am
Edit:

I found out there is an example how to widen resolution and use 16 bit register fully , with pwmWriteHR ....

sorry for OT
Title: Re: PWM frequency library
Post by: Gojr on Apr 09, 2017, 04:10 am
I'm curious what you fixed.  I've noticed that occasionally the PWM doesn't start immediately.  The PWM output will be high or low for 5-10mS before the pulses start.

I am using an Arduino Uno with this library.   Does anyone know what causes these errors or how to fix them?  Attached is an image showing the significant error periodically occurring at the beginning of the PWM signal of an output when viewed on a logic analyzer.   
Title: Re: PWM frequency library
Post by: fred555 on Apr 10, 2017, 05:55 pm
Hi,

I have to make a project where PWM frequency should be around 8-9kHz on one pin and also servo library is involved. To test how PWM frequency library works with servo library I whipped together simple sketch with a few lines borrowed from examples. I used Arduino Nano.

When servo is attached to the pin 9 and SetPinFrequencySafe to pins 10 or 11, there is no PWM on these pins; servo works OK
When servo is attached to the pin 9 and SetPinFrequencySafe to pin 3, there is 9kHz PWM on pin 3, but when I turn the pot to change the duty cycle, the actual change happens with delay of 3-4 seconds, very weird indeed; servo works OK

So the question is, can PWM frequency library and servo library work reliably together and what pins should I use. I need 1 pin for PWM and 1 pin for servo.

Thank you beforehand,
Fred

Here is the code I used for testing

Code: [Select]

#include <PWM.h>
#include <Servo.h> 

int32_t frequency = 9000; //frequency (in Hz)

int servoPin = 9;
Servo servo;
int angle = 0; // servo position in degrees

void setup()
{

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

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

  }

 
  servo.attach(servoPin);
 
}

void loop()
{
 
  int sensorValue = analogRead(A0);
  pwmWrite (10, sensorValue / 4);
 
  delay(30);   
 
// scan from 0 to 180 degrees
  for(angle = 0; angle < 180; angle++) 
  {                                 
    servo.write(angle);               
    delay(15);                   
  }
  // now scan back from 180 to 0 degrees
  for(angle = 180; angle > 0; angle--)   
  {                               
    servo.write(angle);           
    delay(15);       
  }

 
}
Title: Re: PWM frequency library
Post by: Pennypicker on Apr 28, 2017, 07:51 am
Please Help! I got the code below to work. I sent the PWM signal into  Motor Driver BTS7960 43A. The motor speeds up and slows down as expected. But I want to control the DUTY CYCLE to change speed NOT the frequency. PWM Noise must not be heard so I have set the PWM frequency to 21,000hz.

Thanks




 Mimics the fade example but with an extra parameter for frequency. It should dim but with a flicker
 because the frequency has been set low enough for the human eye to detect. This flicker is easiest to see when
 the LED is moving with respect to the eye and when it is between about 20% - 60% brighness. The library
 allows for a frequency range from 1Hz - 2MHz on 16 bit timers and 31Hz - 2 MHz on 8 bit timers. When
 SetPinFrequency()/SetPinFrequencySafe() is called, a bool is returned which can be tested to verify the
 frequency was actually changed.
 
 This example runs on mega and uno.
 */

#include <PWM.h>

//use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
int led = 9;                // 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 = 35; //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, turn pin 13 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);     
}

Title: Re: PWM frequency library
Post by: gonn on May 02, 2017, 10:41 am
hi,
I have read every post of every page but can not able to compile library with ide 1.8
getting, 'InitTimersSafe' was not declared in this scope
can someone run it in latest ides ?
Title: Re: PWM frequency library
Post by: dtr on May 10, 2017, 05:28 pm
Hi,
I'm seeing strange behavior of the pwmWriteHR() function on a Mega (not an official Arduino one). I'm not 100% what the board model is. It has an ATmega1280 processor though.

With attached code I see that pin 3 is getting the PWM set for pin 2 and pin 8 gets the output set for pin 7. Though I have to set a PWM value for 3 and 8 or no output will be given. So setting a value for a pin enables output but it gets the value set for the previous pin.

When I use analogWrite() I'm seeing normal behavior.

Arduino IDE 1.8.1 on Win10.

Is it my code or a library bug?

Code: [Select]

#include <PWM.h>

int led = 11;

void setup() {

 Serial.begin(115200);

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

  //SetPinFrequency(led, 15625);  //setting the frequency
  SetPinFrequency(2, 31250);
  SetPinFrequency(3, 31250);
  SetPinFrequency(5, 31250);
  SetPinFrequency(6, 31250);
  SetPinFrequency(7, 31250);
  SetPinFrequency(8, 31250);
  
  Serial.println("TIMER1");
  uint16_t frequency = Timer1_GetFrequency();
  uint16_t decimalResolution = Timer1_GetTop() + 1;
  uint16_t binaryResolution = GetPinResolution(led); //this number will be inaccurately low because the float is being truncated to a int

  char strOut[75];
  sprintf(strOut, "Frequency: %u Hz\r\n Number of Possible Duties: %u\r\n Resolution: %u bit\r\n", frequency, decimalResolution, binaryResolution );

  Serial.println(strOut);

  Serial.println("TIMER2");
   frequency = Timer2_GetFrequency();
   decimalResolution = Timer2_GetTop() + 1;
   binaryResolution = GetPinResolution(led); //this number will be inaccurately low because the float is being truncated to a int

   strOut[75];
  sprintf(strOut, "Frequency: %u Hz\r\n Number of Possible Duties: %u\r\n Resolution: %u bit\r\n", frequency, decimalResolution, binaryResolution );

  Serial.println(strOut);

  Serial.println("TIMER3");
   frequency = Timer3_GetFrequency();
   decimalResolution = Timer3_GetTop() + 1;
   binaryResolution = GetPinResolution(led); //this number will be inaccurately low because the float is being truncated to a int

   strOut[75];
  sprintf(strOut, "Frequency: %u Hz\r\n Number of Possible Duties: %u\r\n Resolution: %u bit\r\n", frequency, decimalResolution, binaryResolution );

  Serial.println(strOut);
  
  Serial.println("TIMER4");
   frequency = Timer4_GetFrequency();
   decimalResolution = Timer4_GetTop() + 1;
   binaryResolution = GetPinResolution(led); //this number will be inaccurately low because the float is being truncated to a int

   strOut[75];
  sprintf(strOut, "Frequency: %u Hz\r\n Number of Possible Duties: %u\r\n Resolution: %u bit\r\n", frequency, decimalResolution, binaryResolution );

  Serial.println(strOut);

 
}


unsigned int value = 0;
 int value2 = 0;
 int value3 = 0;
int dir = 0;


void loop() {


  pwmWriteHR(2, 32000); // ?
  pwmWriteHR(3, 0); // ?

  pwmWriteHR(7, 5000);
  pwmWriteHR(8, value);

  value = (value + 10) % 65536;
  value2 = (value2 + 5) % 65536;

//delay(1);

}
Title: Re: PWM frequency library
Post by: dtr on May 11, 2017, 05:46 pm
My problem posted just above is solved by texmit's fix earlier in this thread: http://forum.arduino.cc/index.php?topic=117425.msg2854538#msg2854538

That fix was posted almost a year ago. Too bad the library owner seems to have orphaned it. It's a mighty useful one.
Title: Re: PWM frequency library
Post by: karlinbcn on May 17, 2017, 02:00 pm
Hi.
First of all please accept my apologies if I'm not able to explain my doubts in a right way. I'm pretty new to arduino and PWM is hard to understand for me.

First:
Is it possible with this library to generate fractional frequencies? I mean 5.2Hz 34.23Hz and so on.
I ask this because I see in the examples that is always an integer, in fact defined as int32_t

Second:
I don't understand how the instructions works...
SetPinFrequencySafe(led, frequency); Set Led Pin to frequency Hz
Then if success we turn the pin ON and HIGH... At this moment is the signal in the pin?

In  pwmWrite(led, brightness); What is brightness, is it not the frequency? Is it the duty cycle?

Third:
To change the frequency in running time is SetPinFrequencySafe needed or pwmWrite can do the job?



Thanks and best regards



Title: Re: PWM frequency library
Post by: EdwardHarry on Jun 07, 2017, 10:23 am
Dear Brothers, firstly sorry for bad english, my arduino is Arduino MEGA 2560, i want to learn how to change frequency and search the library for it, and find the google code link below :

https://code.google.com/p/arduino-pwm-frequency-library/downloads/list

and downloaded the  5th Version of it >> unzip it in the arduino.ide library on my computer, im sure that i follow this step of adding library :

https://www.arduino.cc/en/guide/libraries

btw my arduino.ide version is 1.8.2

why i cannot compile or even upload the example program ?
it said :

Arduino: 1.8.2 (Windows Store 1.8.3.0) (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\*****\Arduino\sketch_jun07a\sketch_jun07a.ino:1:17: fatal error: PWM.h: No such file or directory

 #include <PWM.h>

                 ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.


my teacher said that i must search the library for arduino mega instead of arduino uno (?), is that right ? is there any solution ?
Title: Re: PWM frequency library
Post by: ballscrewbob on Jun 07, 2017, 02:57 pm
Your teacher is wrong i'm afraid as both the UNO and MEGA use similar AVR architecture.

There is a good comparison link HERE (https://www.arduinostarterkits.com/reviews/arduino-mega-vs-uno-compared/)

Clearly The mega has more pins due to the difference in processor but the lib should still be capable of handling that aspect.
Title: Re: PWM frequency library
Post by: CrossRoads on Jun 07, 2017, 03:01 pm
More likely the library has been put in the wrong location.
Using <PWM.h> requires the files to be in the /libraries folder.
Using "PWM.h" requires the files to be in same folder as the sketch.
Title: Re: PWM frequency library
Post by: oyakodon on Jun 12, 2017, 02:46 am
Hi Everyone, I'm new here ;]

Just wanted to say that this is an excellent PWM library and you guys are an awesome community!

I was wondering if anyone has tried using interrupts with this library? Let's say to just count the number of positive-edge pulses, then if a threshold is reached, stop the pwm?

Perhaps something along the lines of ISR(Timer1_compa_vect)?

Thanks,
Oyakodon
Title: Re: PWM frequency library
Post by: hugoabreu on Jun 12, 2017, 09:10 pm
Hi there,

Do you guys think that's possible to make a Frequency sweep with this librarie?

I was trying to build one, but I'm not sure of what I am missing, or if it is possible indeed.

please, If you want to take a look in my code bellow:

Code: [Select]

     FPWM = lgf[lx]; // This is the frequency of the PWM that im obtainning from another function.

     Init: InitTimersSafe();
   //sets the frequency for the specified pin
     success = SetPinFrequencySafe(SPWM, FPWM);
   //initialize all timers except for 0, to save time keeping functions
   
   if (success)   //here its where I would change my PWM frequency, if success.
   {
     cdelay = 1;
     VL = 0;
     sumvL = 0;
     if (readFlag == 1)
     {
       readFlag = 0;
     }
     while (VL <= cdelay)
     {
       //use this functions instead of analogWrite on 'initialized' pins
       pwmWrite(SPWM, LPWM);  // more precisely here.
       if (readFlag == 1)
       {
         sumvL = sumvL + analogVal;
         VL++;
         readFlag = 0;
       }
     }
     Vs[lx] = sumvL / VL;
   }
   else
   goto Init; //If success is not ok I would go back to InitTimersSafe() line.
   
Thank you for the attention and sorry for bad english.
Title: Re: PWM frequency library
Post by: ballscrewbob on Jun 12, 2017, 09:12 pm
@ hugoabreu

sudo code ?

Title: Re: PWM frequency library
Post by: hugoabreu on Jun 19, 2017, 06:22 pm
Hi.

This code I've put its inside the for loop. I didn't put everything couse, its too long and it doesn't matter.

My main question is if you think that we can change frequencies of PWM inside a for loop.

Ty
Title: Re: PWM frequency library
Post by: ballscrewbob on Jun 19, 2017, 06:55 pm
@hugoabreu

All code matters.
Without it nobody can tell if its good or bad or could be improved in any way or even broken into better segments etc.

And yes it should be possible to call a change inside a loop.
However you should realise that in doing so timers and interrupts could also be changed with unforeseen results unless you account for them.


Title: Re: PWM frequency library
Post by: Prithul on Jun 30, 2017, 08:41 am
Thanks a lot. This library is AWESOME.

I was able to get 100kHz PWM with 16 bit resolution!
Title: Re: PWM frequency library
Post by: J-M-L on Sep 03, 2017, 05:08 pm
I'm experiencing an issue between a UNO and MEGA - my problem is described in a new post (http://forum.arduino.cc/index.php?topic=498258.0) (did not notice this thread was still active, assumed it was too old)

Title: Re: PWM frequency library
Post by: phischmi on Oct 16, 2017, 06:42 am
Hi all,
this is really a great library - very helpful :)

There's just one thing, that's bugging me. Each time, i include the lib in any of my programs, i get some warnings during the compiling.

Code: [Select]

/Users/philipp/Documents/Arduino/libraries/PWM/utility/BTimerDefs.cpp:26:0: warning: "UINT16_MAX" redefined
 #define UINT16_MAX 65535

 ^
In file included from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/lib/gcc/avr/4.9.2/include/stdint.h:9:0,
                 from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/inttypes.h:37,
                 from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/avr/sfr_defs.h:126,
                 from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/avr/io.h:99,
                 from /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino/wiring_private.h:26,
                 from /Users/philipp/Documents/Arduino/libraries/PWM/utility/BTimerDefs.cpp:23:
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/stdint.h:346:0: note: this is the location of the previous definition
 #define UINT16_MAX (__CONCAT(INT16_MAX, U) * 2U + 1U)
 ^
/Users/philipp/Documents/Arduino/libraries/PWM/utility/BTimerDefs.cpp:27:0: warning: "UINT8_MAX" redefined
 #define UINT8_MAX 255

 ^
In file included from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/lib/gcc/avr/4.9.2/include/stdint.h:9:0,
                 from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/inttypes.h:37,
                 from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/avr/sfr_defs.h:126,
                 from /Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/avr/io.h:99,
                 from /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino/wiring_private.h:26,
                 from /Users/philipp/Documents/Arduino/libraries/PWM/utility/BTimerDefs.cpp:23:
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/stdint.h:331:0: note: this is the location of the previous definition
 #define UINT8_MAX (INT8_MAX * 2 + 1)
 ^
Sketch uses 6508 bytes (20%) of program storage space. Maximum is 32256 bytes.
Global variables use 258 bytes (12%) of dynamic memory, leaving 1790 bytes for local variables. Maximum is 2048 bytes.


Nevertheless the code compiles and works fine.

Is someone else having the same problems and how can i solve this?


Thank you all!


Philipp
Title: Re: PWM frequency library
Post by: J-M-L on Oct 16, 2017, 07:06 am
looks like two developers got the same name idea for a #define... the second one reinventing the wheel from stdint.h (https://github.com/f32c/arduino/blob/master/hardware/fpga/f32c/system/include/stdint.h) which has been here for more than 18 years and is better written....(it's a header file in the C standard library introduced in the C99 standard library section 7.18 to allow programmers to write more portable code)


you could go modify the library and put a test to see if it's already defined, something like
Code: [Select]
#ifndef UINT8_MAX
#define UINT8_MAX 255
#endif


but you could also  simply remove them (possibly #include <stdint.h> but I think is added automatically hence the compiler barking at the redefinition - to be tested)
Title: Re: PWM frequency library
Post by: phischmi on Oct 16, 2017, 10:40 pm
Thank you!
I just altered ATimerDefs.cpp and BTimerDefs.cpp.

Changed
Code: [Select]

#define UINT16_MAX 65535
#define UINT8_MAX 255


to
Code: [Select]

#ifndef UINT16_MAX
#define UINT16_MAX 65535
#endif
#ifndef UINT8_MAX
#define UINT8_MAX 255
#endif


in both files.

Works and the compiler is not barking anymore :)
Title: Re: PWM frequency library
Post by: Uup115 on Nov 20, 2017, 04:10 pm
Very nice library indeed!

Regarding the frequency sweep, hugoabreu mentioned...  I'm actually doing that for a project, using the Arduino Pro Mini (sweeping from 1 Hz to 500 Hz, with a 1 Hz step size, transitioning steps every 1000 - 2000 msec).  Simply set the frequency and duty cycle for each frequency step:

Code: [Select]

if (SetPinFrequencySafe(led, frequency))
{
       pwmWrite(led, brightness);
}


Only one problem...  The frequency steps sometimes do not transition smoothly.  Meaning, the output will glitch and stick in the high or low state, for up to a second, before stabilizing at the new frequency/duty cycle.   In my use case, the duty cycle remains constant throughout the sweep.  

Unfortunately, for me, this is not good.  Sweeping with these glitches is causing problems with connected device(s).  Has anyone else encountered this problem?  Is there a fix for it?  Any assistance is appreciated.
Title: Re: PWM frequency library
Post by: phatpaul on Dec 01, 2017, 12:53 am
I noticed the same issue that Uup115 reported.  The frequency does not transition smoothly.  Also the frequency is not exact (off by ~0.5%).  This is due to the ceramic osc. used on the Uno and Mega.  The Leonardo has a crystal osc. with much higher accuracy, but was not supported by this library.

So I forked the library and improved it with the following.



You can find the updated code here: https://github.com/phatpaul/arduino-pwm-frequency-library

Hope it helps,
Paul
Title: Re: PWM frequency library
Post by: Briney_Eye on Dec 17, 2017, 07:41 pm
It would seem that you changed things so that InitTimers() and InitTimersSafe() now require a minimum frequency argument, breaking everyone's existing code.  Could you explain that?  I'm just getting started reading through the timer section of the ATmega data sheet.
Title: Re: PWM frequency library
Post by: sthudium on Dec 18, 2017, 07:18 pm
Does this library work with the Arduino Zero, which has a SAMD processor?

If not, can someone make the necessary changes?
Title: Re: PWM frequency library
Post by: usertogo on Dec 26, 2017, 02:13 pm
Aloha very happy to see that people are still using the library successfully! I once tested it out and all worked great, but now years later different IDE version (latest on Linux arduino-1.8.5-linux64.tar ) I have a problem getting the library to install, I am using V_05 from: https://code.google.com/archive/p/arduino-pwm-frequency-library/downloads
Regardless of how I put it the IDE complains about the package 'does not contain a valid library'...
It seems nobody has worked on the code since the end of 2012, what could cause this error in my IDE? Any suggestions or workarounds are highly appreciated!

PS: I think I just found the solution in post #126 of this thread (tab 9) a user posted a fixed PWM.zip library, which installed fine and I am onto troubleshooting the rest of my adventure...
Title: Re: PWM frequency library
Post by: usertogo on Dec 26, 2017, 03:27 pm
Hi i have tried to contact the supporter of the library "runnerup". i have some minor fixes to the library i have created a zip compatible with newer versions of arduino. does anyone knows how to contact runnerup?
Would be great if you could upload it at a Git site or so, if the license permits?
And we are all very curious what it was that caused the library to fail to install in those newer IDEs?
Title: Re: PWM frequency library
Post by: Trimjohan on Jan 09, 2018, 02:30 am
It would seem that you changed things so that InitTimers() and InitTimersSafe() now require a minimum frequency argument, breaking everyone's existing code.  Could you explain that?  I'm just getting started reading through the timer section of the ATmega data sheet.

+1
Yes that is wierd...
Title: Re: PWM frequency library
Post by: Trimjohan on Jan 09, 2018, 11:15 am
Hi i have tried to contact the supporter of the library "runnerup". i have some minor fixes to the library i have created a zip compatible with newer versions of arduino. does anyone knows how to contact runnerup?
Great Job with the library! Meninas's version above works flawless for me.

Here is a neat example how to use PWM frequency library by Riham.

https://codebender.cc/sketch:211750#PWM%20Frequency%20Library%20Example.ino

This library really is perfect if you need a lower PWM frequency for solenoids.
As we we all know they need PWM frequencies around 8-40 hz to function properly.

Title: Re: PWM frequency library
Post by: Uup115 on Jan 11, 2018, 09:21 pm
I noticed the same issue that Uup115 reported.  The frequency does not transition smoothly.  Also the frequency is not exact (off by ~0.5%).  This is due to the ceramic osc. used on the Uno and Mega.  The Leonardo has a crystal osc. with much higher accuracy, but was not supported by this library.

So I forked the library and improved it with the following.

  • Added support for ATmega16U4/32U4 (Leonardo) by "Pierre" Oct 23, 2013. Copied from https://code.google.com/archive/p/arduino-pwm-frequency-library/issues/2
  • Modified to avoid changing prescaler when changing frequency by Paul Abbott - 2017


You can find the updated code here: https://github.com/phatpaul/arduino-pwm-frequency-library

Hope it helps,
Paul
Paul, nice work!  I've been reluctantly accepting these glitches, until I could find another solution.  Unfortunately, I'm not savvy enough to do what you did.

Many thanks!

Best Regards,
Uup115

Title: Re: PWM frequency library
Post by: rholk on Jan 16, 2018, 05:29 pm
Hi,

I have some problem with this library using an arduino mega:

I want to pilot 4 fans (classic pc pwm).


On my setup() i have:
Code: [Select]

InitTimersSafe();

tryF(2, frequency); // Front fan 1 t3B
tryF(3, frequency); // Front fan 2 t3C
tryF(5, frequency); // Front fan 3 t3A
tryF(6, frequency); // Front fan 4 t4A
  Serial.print("t3:");
  Serial.print(Timer3_GetFrequency());
  Serial.print("\nt4:");
  Serial.print(Timer4_GetFrequency());



tryF function:
Code: [Select]

void tryF(int8_t pin, int32_t freq)
{
  //sets the frequency for the specified pin
  bool success = SetPinFrequencySafe(pin, freq);

  if (success) {
    set(pin, 0);
    Serial.print(pin);
    Serial.print("=>");
    Serial.print(freq);
    Serial.print(": SUCCESS\n");
  } else {
    Serial.print(pin);
    Serial.print("=>");
    Serial.print(freq);
    Serial.print(": FAIL\n");
  }
}


And then, i have  a set function callable by serial
Code: [Select]

void set(uint8_t pin, uint16_t val)
{
  Serial.print("Applicating ");
  Serial.print(pin);
  Serial.print("/");
  Serial.print(val);
  Serial.print("\n");
  pwmWriteHR(pin, val);
}





At the begin of my soft i have:
Code: [Select]

mega: init...
mega: Applicating 2/0
mega: 2=>25000: SUCCESS
mega: Applicating 3/0
mega: 3=>25000: SUCCESS
mega: Applicating 5/0
mega: 5=>25000: SUCCESS
mega: Applicating 6/0
mega: 6=>25000: SUCCESS
mega: init done (pwm)
mega: t3:25000
mega: t4:25000


So everything is fine and i see my fan throttle down to 500 rpm (hall detection on pins 21 20 19 18).
If i call set(2, 65535), my fan 1 goes to max speed (~1600 rpm) and not the others.
RPM:1695,540,570,525
If i call set(5, 65535), my fan 3 goes to max speed (~1600 rpm).
RPM:1650,540,1605,510

My problem is when i use for example:
set(5, 32767), my rpm report is strange:
RPM:1050,555,1620,525 => fan 1 on pin 2 have it's speed reduced!

I don't know where is the bad behavior of my soft. can someone help me?

Electricaly, pins of the arduino are directly connected to the pwm of the fan. Ground / 12v is supplied by an ATX power supply.
Same supply powers the PC piloting the arduino, threw usb.
Possibly ground issue?

Complete code linked.
Title: Re: PWM frequency library
Post by: Jelmer_ on Jan 20, 2018, 12:16 pm
Hi,
Is there also a way to get a more precise frequency. Because i need a frequency of about 80.4 hz. Can i send a float in the function or is there some other method?
Title: Re: PWM frequency library
Post by: asgeiro on Jan 25, 2018, 05:40 pm
Hi,
I am working on a light control project, and i need 16 PWM pins with exactly 100Hz, and individually alter the dutycycle. I need to Control 16 dimmers this way, so I can co it either with 3 UNO´s or 2 Mega´s.
On Uno, 4 pins work, and 2 gives me error.
On Mega I experience weird behaviour on most of the pins, and 2 gives me error. They do not give the correct DutyCycle. Here follows the code examples for both boards. I have measured the dutycycle with picoscope, and written the results commented into the code below. Do you have Any Idea how I can achieve my goal using this Library?

Code: [Select]
//CODE FOR MEGA

#include <PWM.h>


void setup() {

 Serial.begin(9600);
 InitTimers();
 if (!SetPinFrequency(2, 100))Serial.println("PWM pin 2 failed.");
 if (!SetPinFrequency(3, 100))Serial.println("PWM pin 3 failed.");
 if (!SetPinFrequency(4, 100))Serial.println("PWM pin 4 failed.");
 if (!SetPinFrequency(5, 100))Serial.println("PWM pin 5 failed.");
 if (!SetPinFrequency(6, 100))Serial.println("PWM pin 6 failed.");
 if (!SetPinFrequency(8, 100))Serial.println("PWM pin 7 failed.");
 if (!SetPinFrequency(9, 100))Serial.println("PWM pin 8 failed.");
 if (!SetPinFrequency(10, 100))Serial.println("PWM pin 9 failed.");
 if (!SetPinFrequency(11, 100))Serial.println("PWM pin 10 failed.");
 if (!SetPinFrequency(12, 100))Serial.println("PWM pin 11 failed.");
 if (!SetPinFrequency(13, 100))Serial.println("PWM pin 12 failed.");
 Serial.println("Running..");
}
void loop() {

 pwmWrite(2, 25);    //Should have been ca 10%, actual is 40% not changed by changing 25
 pwmWrite(3, 51);    //Should have been ca 20%, actual is 10% seemes to be changing with pin 2
 pwmWrite(4, 76);    //Should have been ca 30%, actual is 30%
 pwmWrite(5, 102);   //Should have been ca 40%, actual is 80%
 pwmWrite(6, 127);   //Should have been ca 50%, actual is 20%
 pwmWrite(7, 153);   //Should have been ca 60%, actual is50%
 pwmWrite(8, 177);   //Should have been ca 70%, actual is60%
 pwmWrite(9, 204);   //Should have been ca 80%, actual is90%
 pwmWrite(10, 230);  //No duty cycle
 pwmWrite(11, 204);  //Should have been ca 80%, actual is80%
 pwmWrite(12, 177);  //Should have been ca 70%, actual is70%
 pwmWrite(13, 153);  //No duty cycle

 delay(30);
}

//CODE FOR UNO

#include <PWM.h>


void setup() {

 Serial.begin(9600);
 InitTimers();
 if (!SetPinFrequency(3, 100))Serial.println("PWM pin 3 failed.");
 if (!SetPinFrequency(5, 100))Serial.println("PWM pin 5 failed.");
 if (!SetPinFrequency(6, 100))Serial.println("PWM pin 6 failed.");
 if (!SetPinFrequency(9, 100))Serial.println("PWM pin 9 failed.");
 if (!SetPinFrequency(10, 100))Serial.println("PWM pin 10 failed.");
 if (!SetPinFrequency(11, 100))Serial.println("PWM pin 11 failed.");
 Serial.println("Running..");
}
void loop() {

 pwmWrite(3, 26);    //DutyCycle 10% OK
 pwmWrite(5, 51);    //DutyCycle 20% OK
 pwmWrite(6, 76);    //No duty cycle
 pwmWrite(9, 102);   //DutyCycle 40% OK
 pwmWrite(10, 127);  //DutyCycle 50% OK
 pwmWrite(11, 153);  //No duty cycle
 delay(30);
}
Title: Re: PWM frequency library
Post by: rholk on Jan 30, 2018, 11:34 am
I don't know why, but i feel this library is deprecated somehow. The github repository do no allow to send messages / issue to the owner.

Possibly the library work with an older arduino IDE?
Title: Re: PWM frequency library
Post by: JacksonAudio on Feb 16, 2018, 01:48 am
Has anyone been able to compile this for the Atmega1284? I'm using the MightyCore bootloader and I get the following message every time I try and compile:

Arduino: 1.8.4 (Mac OS X), Board: "ATmega1284, Standard, 1284, 2.7v, Disabled (default), 20 MHz external"

Build options changed, rebuilding all
sketch/PWM_lib_example.ino.cpp.o: In function `setup':
/Users/BradJackson/Google Drive/Jackson Ampworks/Arduino/PWM_lib_example/PWM_lib_example.ino:24: undefined reference to `InitTimersSafe()'
/Users/BradJackson/Google Drive/Jackson Ampworks/Arduino/PWM_lib_example/PWM_lib_example.ino:27: undefined reference to `SetPinFrequencySafe(signed char, unsigned long)'
sketch/PWM_lib_example.ino.cpp.o: In function `loop':
/Users/BradJackson/Google Drive/Jackson Ampworks/Arduino/PWM_lib_example/PWM_lib_example.ino:39: undefined reference to `pwmWrite(unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board ATmega1284.
Title: Re: PWM frequency library
Post by: seggi on Apr 24, 2018, 12:57 pm
Hello


I am using arduino nano can i generate 7 mhz pwm signal with 50%duty cycle ?
if yes then guide me How Can i generate ?

Best Regards
seggi.
Title: Re: PWM frequency library
Post by: AmmarAl-Gizi on May 04, 2018, 12:03 am
This Library didn't work. The following message was appeared:
 
The library "Arduino PWM Frequency Library v_05" cannot be used.
Library names must contain only basic letters and numbers.
(ASCII only and no spaces, and it cannot start with a number)

Please, I need it!
Title: Re: PWM frequency library
Post by: AmmarAl-Gizi on May 04, 2018, 12:23 am
Hi, could anyone help me?
I have noticed that there's no PWM.cpp file. The library wasn't installed.
Title: Re: PWM frequency library
Post by: Gryskop on May 11, 2018, 04:50 pm
You extracted the filename of the zip file directly into your library directory as "Arduino PWM Frequency Library v_05"
You should simply make a directory under libraries and call it PWM for example.
C:\Program Files\arduino-1.8.1\libraries\PWM

Then copy all the stuff in under the PWM directory into this new library PWM directory, and copy PWM_lib_example and PWM_lib_resolution_example into there as well.

It should look like this when your done ...

 Directory of C:\Program Files\arduino-1.8.1\libraries\PWM

11-May-2018  16:49    <DIR>          .
11-May-2018  16:49    <DIR>          ..
16-Aug-2012  16:55             2,208 keywords.txt
24-Sep-2012  15:24             4,873 PWM.h
11-May-2018  14:38    <DIR>          PWM_lib_example
11-May-2018  14:38    <DIR>          PWM_lib_resolution_example
11-May-2018  16:49                 0 showDir.txt
11-May-2018  14:38    <DIR>          utility
               3 File(s)          7,081 bytes
               5 Dir(s)  113,831,374,848 bytes free
Title: Re: PWM frequency library
Post by: frobi on Jun 14, 2018, 08:36 pm
Hello
I like to using this pwm.h librari variable phase shifting arduino between two pwm chanel.
I like the shifing variable 0-180 degrees.

Somebody doing same?

thanks!
Title: Re: PWM frequency library
Post by: Sudipta_mandal94 on Jul 06, 2018, 03:37 pm
Cannot compile the code for Atmega8. While I tried compiling for Atmega168, the code uses 2720 bytes of space and compiles successfully and works fine. Anyone please help me.
Title: Re: PWM frequency library
Post by: PlankSpank on Jul 16, 2018, 05:38 pm
post your code if you want help
Title: Re: PWM frequency library
Post by: citrusying on Jul 29, 2018, 10:35 pm
Hi

I am trying to lower the Arduino Uno PWM frequencies to drive 4 x solenoid valves. Ideally, pins 5 & 6 are untouched to retain timer0 function. However, understand that creating custom frequencies would sacrifice 2 pins on Arduino, which I have found out to be pins 6 and 11. 


In the original post by runnerup:
"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. "

So if I would like to leave pins 5 and 6 untouched and change PWM frequency for pins 3, 9, 10 AND 11 to 31Hz? Do I simply use this setup to change the timer prescaler and the PWM frequencies for the 4 pins would be lowered to 31Hz?

Code: [Select]
void setup()
{
Timer1_SetPrescaler(ps_1024);
Timer2_SetPrescaler(psalt_1024);
}


I tried doing that and alternatively using this function PwmFrequency (https://playground.arduino.cc/Code/PwmFrequency) to also change the prescaler. But neither works.

So is this a limitation such pins 6 and 11 cannot be used?

Appreciate some clarification/ advice, thanks!
Title: Re: PWM frequency library
Post by: Trance_Paradox on Sep 02, 2018, 10:56 am
Great Library


Some problems i am facing:
1- Cannot modify the frequency of pin 11, the bool doesn't return success
2- Can't get the resolution on pin 3 and 11 although the timer gives me resolution
Title: Re: PWM frequency library
Post by: Serhij-Demyanuk on Mar 08, 2019, 10:10 pm
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.
I am using Atmega 64/128/256 with MegaCore , your library is very necessary for me for one project. But it does not support this processor. Can you help me? Thanks.
Title: will this library work for arduino MKR wifi 1010
Post by: Ayman1993 on Apr 18, 2019, 04:48 am
I've tried implementing the library and i get an error, i thought this was supposed to work for all Arduinos?
Title: Re: PWM frequency library
Post by: ballscrewbob on Apr 18, 2019, 05:18 am
@Ayman1993

Not ALL libraries are meant for ALL Arduinos.
Which Library the one in question already or a different one ?

What board are you trying to use your lib with ?

Ok less questions and more directions.
Please read the sticky posts at the top of forum sections and add the details they recommend.