How to Change the Frequency on Arduino PWM Pins

Arduino Pwm Frequency Featured

Arduino hardware is great for IoT projects, but if you’re just getting your feet wet, it can be a little confusing. Much of the code you’ll need to write is straightforward, but once you have to interact with different hardware, the code can start getting more complex.

PWM pins are a great example of this. They enable you to work with a variety of different hardware and control it in many ways, but if you don’t come from an electrical background, they can seem tough to deal with.

What Does PWM Do on Arduino?

PWM stands for Pulse Width Modulation. This is a digital square wave where the frequency stays the same, but how often that signal is being sent is adjustable. Without context, that doesn’t mean much.

Pulse Width Modulation lets you do many useful things. This includes sending audio signals, controlling variable speed motors, or providing variable current to dim LEDs and similar functions.

Can’t You Just Use the analogWrite() Command?

For most users, the analogWrite() command will do all you need, but as mentioned above, the frequency is fixed. This is fine for many use cases, but not all of them.

Arduino Pwm Frequency Pwm

Each pin has a default frequency. This differs per pin, but they are still within a fairly close range of one another. The highest default frequency is still under 1,000 Hz, which isn’t enough for all use cases.

Manipulating PWM Timers Directly

You can manually set PWM frequencies by manipulating the time registers. There are a total of three of these, each controlling two PWM outputs each, Timer 0, Timer 1, and Timer 2. There are two ways to control the frequencies: Fast PWM, and Phase Correct PWM.

Below is an example of Fast PWM from the Arduino website:

This would yield a frequency of 976.5625Hz, using the following math:

Below is an example of Phase Correct PWM from the same website:

This provides an output frequency of 490.196Hz, using the following math:

Manually Controlling PWM Pin Frequencies

Arduino Pwm Frequency Due

Another option is to manually switch a pin on and off at the desired rate. The bonus here is that it lets you use any pin, not just the dedicated PWM pins.

Here is another example from the Arduino website:

There are a few issues with this method. One is that interrupts will affect the timing, which could cause problems. You’re also effectively limiting the Arduino to just doing this while it is running.

Conclusion

Now that you understand how to change the frequency of PWM pins on an Arduino board, you’ve opened up a lot of options. To see just how much you can do, why not get started building something?

If you’re new to Arduino in general, you’ll probably still run into the occasional stumbling block along the way. If that’s the case, be sure to keep our Arduino cheat sheet within reach.