PWM frequency library

Anyone know why pin 11 on timer2 doesn't work?

All the rest work great.

I'm using the Uno.

Cheers

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!

go see this ... AccelStepper: AccelStepper library for Arduino

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.

Thanks for this library!

Petit-Jean:
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.

Many thanks in advance!
Christophe aka Petit Jean

Any luck with Arduino Leonardo?
Thank you

@Talhaamjad,
Please don't crosspost. I see this same request in Project Guidance. Duplicate is being deleted.
Moderator.

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.

i think is the new library system, it need to be updated

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

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!

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