62.5KHz PWM USING ARDUINO

Photo of author

By Jackson Taylor

Home » Electronics Topics » Arduino » 62.5KHz PWM USING ARDUINO

As an Amazon Associate we earn from qualifying purchases.

By default, an Arduino Uno outputs PWM at about 490 Hz on most pins and about 976 Hz on pins 5 and 6. That is fine for dimming an LED, but it is too low for many power electronics, audio filtering and fast motor-drive jobs. This article shows how to raise the frequency of pin 6 to 62.5 kHz, the highest the hardware offers on these pins without changing the timer mode.

The method works by changing the timer prescaler. It uses only a few lines of code and no extra library. The sketch below is written for ATmega328-based boards such as the Uno and Nano running at 16 MHz.

Why PWM frequency matters

PWM switches a pin on and off quickly, and the duty cycle sets the average output. The frequency decides how fast that switching happens. A higher frequency helps in several situations:

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
  • Switching supplies and small DC-DC converters can use smaller inductors and capacitors.
  • Motors and coils run more quietly because the switching noise moves above the audible range.
  • An RC low-pass filter gives a smoother analog voltage because it has less ripple to remove.
  • LED dimming shows less flicker on cameras.

If you are new to the topic, our article on artificial PWM and sine waves covers the basics of duty cycle and averaging.

How Arduino generates PWM

The ATmega328P has three hardware timers, and each one drives two PWM pins:

  • Timer0: pins 5 and 6
  • Timer1: pins 9 and 10
  • Timer2: pins 3 and 11

Each timer runs from the 16 MHz system clock divided by a prescaler. The Arduino core sets a prescaler of 64 by default. Timer0 runs in fast PWM mode and counts to 255, so its output frequency is 16 MHz / 64 / 256, or about 976 Hz. If you set the prescaler to 1, the frequency becomes 16 MHz / 256 = 62,500 Hz, which is 62.5 kHz.

See also
POWER CONTROL USING IGBT (6KW)

Timers 1 and 2 use phase-correct PWM, which counts up and then down. Their top frequency with a prescaler of 1 is therefore about half as high, roughly 31 kHz. The comments in the code below round this figure to 31250 Hz.

Prescaler settings for pins 5 and 6

Dividing the 62.5 kHz base frequency by each available divisor gives these results:

  • Divisor 1: 62,500 Hz
  • Divisor 8: about 7,812 Hz
  • Divisor 64: about 976 Hz (the default)
  • Divisor 256: about 244 Hz
  • Divisor 1024: about 61 Hz

Arduino code for 62.5 kHz PWM

The sketch below defines a helper function, setPwmFrequency(pin, divisor). It writes the prescaler bits of the timer that controls the chosen pin. In setup(), it sets pin 6 to a divisor of 1 and then calls analogWrite(6, 150). The value 150 out of 255 gives a duty cycle of about 59%.

void setup()
                     {
                     setPwmFrequency(6, 1);
                     analogWrite(6,150);
                     }
                     void loop()
                     {
                     }
                     void setPwmFrequency(int pin, int divisor) {
                       byte mode;
                       if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
                         switch(divisor) {
                           case 1: mode = 0x01; break;
                           case 8: mode = 0x02; break;
                           case 64: mode = 0x03; break;
                           case 256: mode = 0x04; break;
                           case 1024: mode = 0x05; break;
                           default: return;
                         }
                         if(pin == 5 || pin == 6) {
                           TCCR0B = TCCR0B & 0b11111000 | mode;
                         } else {
                           TCCR1B = TCCR1B & 0b11111000 | mode;
                         }
                       } else if(pin == 3 || pin == 11) {
                         switch(divisor) {
                           case 1: mode = 0x01; break;
                           case 8: mode = 0x02; break;
                           case 32: mode = 0x03; break;
                           case 64: mode = 0x04; break;
                           case 128: mode = 0x05; break;
                           case 256: mode = 0x06; break;
                           case 1024: mode = 0x7; break;
                           default: return;
                         }
                         TCCR2B = TCCR2B & 0b11111000 | mode;
                       }
                     }
                     /**
                      * Divides a given PWM pin frequency by a divisor.
                      *
                      * The resulting frequency is equal to the base frequency divided by
                      * the given divisor:
                      *   - Base frequencies:
                      *       o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
                      *       o The base frequency for pins 5 and 6 is 62500 Hz.
                      *   - Divisors:
                      *       o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
                      *         256, and 1024.
                      *       o The divisors available on pins 3 and 11 are: 1, 8, 32, 64,
                      *         128, 256, and 1024.
                      *
                      * PWM frequencies are tied together in pairs of pins. If one in a
                      * pair is changed, the other is also changed to match:
                      *   - Pins 5 and 6 are paired on timer0
                      *   - Pins 9 and 10 are paired on timer1
                      * - Pins 3 and 11 are paired on timer2
                      *
                      * Note that this function will have side effects on anything else
                      * that uses timers:
                      *   - Changes on pins 3, 5, 6, or 11 may cause the delay() and
                      *     millis() functions to stop working. Other timing-related
                      *     functions may also be affected.
                      *   - Changes on pins 9 or 10 will cause the Servo library to function
                      *     incorrectly.
                      *
                      * Thanks to macegr of the Arduino forums for his documentation of the
                      * PWM frequency divisors. His post can be viewed at:
                      *   http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1235060559/0#4
                      *
                      */

How the code works

Each timer has a control register, TCCRnB, and its lowest three bits select the clock prescaler. The line TCCR0B = TCCR0B & 0b11111000 | mode; clears those three bits and writes the new value. The other bits in the register stay unchanged. Writing 0x01 means no prescaling, so the timer runs at the full 16 MHz.

See also
Analysis and Design of a Non-Isolated Bidirectional ZVS-PWM Active Clamped DC-DC Converter

The switch blocks translate a readable divisor, such as 8 or 64, into the matching register value. Timer2 has more prescaler options than timers 0 and 1, which is why the list for pins 3 and 11 is longer.

Side effects to know about

The three timers do other work for the Arduino core, so changing a prescaler has consequences:

  • Timer0 (pins 5 and 6): The core uses this timer for millis(), micros() and delay(). With a divisor of 1, the timer runs 64 times faster than normal, so delay(1000) lasts only about 16 ms. Avoid timing functions in a sketch like this, or scale your delays to compensate.
  • Timer1 (pins 9 and 10): The Servo library depends on this timer, so servos will not work correctly.
  • Timer2 (pins 3 and 11): The tone() function uses this timer.

If you need working delays, move the high-frequency output to pin 9 or 10 (timer1) or to pin 3 or 11 (timer2). Their top frequency is about 31 kHz instead of 62.5 kHz. Pins on the same timer share a frequency, so changing pin 5 also changes pin 6.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

Checking the output

Use an oscilloscope or a logic analyzer to confirm the frequency. A multimeter with a frequency function can also give a rough reading. You should see a square wave at about 62.5 kHz, with a high time of about 59% of each period when you use analogWrite(6, 150). Pins 5 and 6 can show a slightly higher duty cycle than expected at very low values, so check the waveform if you need accuracy there.

At this frequency, keep the wiring short and use a proper driver stage if you switch a MOSFET gate. A bare Arduino pin can only supply a small current, and long leads can add ringing to the edges.

Other boards and microcontrollers

These register names and frequencies apply to the ATmega328P at 16 MHz. A 8 MHz board such as a 3.3 V Pro Mini gives half the frequency. The Arduino Mega and Leonardo use different timers, so check their datasheets before using this code. If you work with other chips, we also cover PWM on the PIC16F877A, simple PWM on the dsPIC30F2010 and PWM light waves on the MSP430G2553.

See also
Arduino ,bluetooth/pc and triac based speed control of ac home fan

FAQ

Why does my delay() stop working after changing the frequency?

Pins 5 and 6 run on timer0, which the Arduino core also uses for delay() and millis(). A prescaler of 1 makes this timer run 64 times faster, so time-based functions run far too quickly. Use a different timer for your PWM pin or adjust your timing values.

Can I get 62.5 kHz on pins 9, 10, 3 or 11?

Not with this method. Those pins use phase-correct PWM, which tops out at around 31 kHz with a prescaler of 1. To go higher, you would have to reconfigure the timer into fast PWM mode by writing its registers directly.

Does analogWrite still control the duty cycle at 62.5 kHz?

Yes. The values 0 to 255 still set the duty cycle. Only the frequency changes.

Is a higher PWM frequency always better?

No. Higher frequencies increase switching losses in transistors and can cause more electrical noise. Choose the lowest frequency that meets your needs, whether that is silent operation, smooth filtering or small passive components.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works