PWM frequency library

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:

My Code so far:

/*  
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:

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

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);
}

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.

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

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

luxornet:
Any luck with Arduino Leonardo?
Thank you

For leonardo I found this article: --> R6500: Fast PWM on Arduino Leonardo
not a ready to use library,
but really good explained how to do...

The Google Code page seems to have been orphaned.

You can see some PWM driving high power motors at
www.electronics-freak.com
Roee

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:

#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

#1. Use code tags. It makes it easier to read code.
4V? Seems like your voltage is not being amplified or something.

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

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.

Hi,

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

1 Like

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

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.

JcanReefMan:
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.

You're welcome

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?

There's no github with this library exported? Google Code is closed! Thanks

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)