HOW TO INCREASE THE PWM FREQUENCY OF THE ARDUINO ON PINS 10, 11(OC1B, OC2A)
HOW TO INCREASE THE PWM FREQUENCY OF THE ARDUINO ON PINS 10, 11(OC1B, OC2A)
This post explains about how to increase the pwm frequency
of digital pins 10 and 11 on Uno, Nano, mini. The default frequency is nearly 500
Hz this trick helps to increase to 31.3 kHz.
Now 500 Hz is ok for many speed and analog controls
but we need more frequency for high speed controlling and high speed switching
like buck and boost, switch mode power supply, RF etc. Applications.
That being said how do we do that…? Well the pwm pins are
actually wired internally to timer circuits. The Arduino (Uno, Mini and Nano)
have 3 timers Timer 0, 1, 2.
[NOTE: this technique will helps to increase
frequency not the bit rate, the bit rate is only 8-bit no matter what (MAX 256bits)]
Here we need to change those timers1 “B” (OC1B or 10 pin),
timer2 “A” (OC2A or 11pin). By changing the Pre-scaler value, changing the
registers value we can accomplish that.
Timer2 (8bit) PWM:
Fast PWM (TOP=0xff), and pre-scaler= 1 are as follows:
“TCCR2B = TCCR2B & B11111000 | B00000001; // put this line in
void setup () for 31.37 kHz on pin 11 and 3“
Down
below the register of the TCCR2B:
7 6 5 4 3 2 1 0
FOC2A |
FOC2B |
WGM20 |
WGM21 |
WGM22 |
CS22 |
CS21 |
CS20 |
Don’t
touch 7 and 6 bits if so they disable pwm mode to compare mode.
We
need to change WGM20, 21, 22 registers value for pre-scaler, I’m setting to
pre-scaler 1. Hence the math goes like this:
Period
T = (1/16 MHz/1)*256 = 0.016ms => Freq F = 1/T = 1/0.016ms = 62.5 KHZ
Timer1 (16bit) PWM:
The above line of code helps you to change the TCCR1B register
TCCR1B:
7 6 5 4 3 2 1 0
ICNC1 |
ICES1 |
|
WGM13 |
WGM12 |
CS12 |
CS11 |
CS10 |
void setup()
{
Serial.begin(9600);
Serial.print(TCCR1B,BIN); //tests what is default in TCCR1B and returns inbinary
TCCR1B = TCCR1B & B11111000 | B00000001;
// put your setup code here, to run once:
//put this in void setup () for generating pwm frequency of //31.383 KHZ
pinMode(10, OUTPUT);
}
void loop()
{
//for(int i=0; i<256 0.9="" 255="" analogwrite="" delay="" for="" i="" int="" j="">=0 ; j-=5){
analogWrite(10, j);
delay(30);
}
*/
}
256>
Comments
Post a Comment