# Generating a High Frequency PWM on Arduino

The filter that we had discussed about in the previous article has PWM pulses as inputs to the Gate terminal of Power MOSFETs used. These PWM pulses should be of high frequency to minimize the ripples in output current.

## Problem with the by default Arduino PWM Frequency :

The by default PWM frequency provided by Arduino is very low, either 490 Hz or 980 Hz.

The simulation results of filter when PWM frequency is taken to be 980 Hz are :

Above picture represents the current through peltier when PWM frequency is 980Hz. As seen in the plot the nature of current is not smooth and the ripple values are very high, this type of current is unsafe for Peltier Element.

When the same circuit is simulated for 50 KHz PWM  Frequency, the simulation results clearly depict that current has very less ripples and is smooth.

So now the question is How do we get a high frequency PWM from Arduino ?

Arduino Board uses ATMEGA328P as Micro-Controller, so we made use of ATMEGA328P’s datasheet to figure out how do we get a High Frequency PWM.

I have attached snapshots of the datasheet along with some explanation of the code that we will use.

## Datasheet Snapshots and explanation:

Since we need a Non-Inverting Fast PWM we will have to set the following bits in register TCCR2A –

1. COM2A1                                 For Non Inverting PWM
2. COM2B1                                 For Non Inverting PWM
3. WGM20 and WGM21          For Fast PWM

We need Fast PWM mode because the output frequency of Phase Correct PWM is approximately half of the value of fast PWM mode.

We need to set Pre-Scalar to 1 which can be done by setting the CS20 bit in TCCR2B Register High.

## Code for obtaining high frequency PWM on Arduino:

void setup()
{
pinMode(3, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20) | _BV(WGM21);
TCCR2B = _BV(CS20);
OCR2B = 126;
}
void loop()
{
OCR2B = 126;
}

The above code gives pulses on Digital Pin 3 of the Arduino, the frequency of this PWM pulses is approximately 54 KHz.

The duty cycle depends on the value stored in register OCR2B, and is equal to
$Duty&space;Cycle&space;=&space;\frac{OCR2B+1}{256}$

So we can change the pulse width by changing the value of register OCR2B between 0 to 255 .

0