PWM on Arduino

I’ve spent a lot of time recently talking about different aspects of PWM and filtering. Today I’d like to take a step back from the theory and build what you might call the “Hello World” of digital synthesis, generating PWM signals with an Arduino. This should be a fairly straightforward project but will give me a vehicle to start experimenting with pulse width modulation in a more concrete setting.

Wiring It Up

Arduino PWM Circuit

The wiring for this one is pretty simple. On one side of the Arduino I’ve placed a 10K potentiometer between 5V and ground with the wiper connected to pin A0. This is the analog input that I will use to set the duty cycle of my pulse. The potentiometer will function as a basic voltage divider allowing us to control the voltage at the pin (between 0 and 5V).

On the other side of the Arduino we find the digital pins. These are where we can output our PWM signal. You’ll notice some of the pins (3, 5, 6, 10 and 11) have a tilde beside them. These are the pins capable of outputting PWM signals. An additional consideration is that Arduino UNO boards offer two different PWM frequencies. Pins 3, 10 and 11 output PWM at 490Hz while pins 5 and 6 output 980Hz. For this project I’ll be connecting my scope to pin 5 to read a signal output at that pin.

Writing The Code

The code for this project should be pretty straight forward as well. I’m writing it using the Arduino IDE which is available free from the Arduino website. I’m going to break it into a few sections and explain each one.

int duty_cycle_in = A0;
int PWM_out = 5;

int duty_cycle;

The first step is to declare a few variables. Here we define our duty cycle control to be at pin A0 and our PWM output to be at pin 5. This step can be skipped if you refer to the pins directly when you use them in your program however as your code grows this can make things really confusing. For the sake of keeping clear and concise code I always alias my pins in this way.

Additionally I create an integer variable to store the duty cycle. This variable will be updated with a value from duty_cycle_in and be used to write the PWM signal to PWM_out.

void setup() {
  pinMode(PWM_out, OUTPUT);
  pinMode(duty_cycle_in, INPUT);
}

Next up is our setup function. This function will run once when the Arduino powers on before moving into the main loop. Here we call the pinMode function twice. This function tells the Arduino what kind of information to expect from/send to each pin. We set PWM_out (pin 5) as an output and duty_cycle_in (pin A0) as an input.

void loop() {
  duty_cycle = analogRead(duty_cycle_in)/4;
  analogWrite(PWM_out, duty_cycle);
}

Finally we come to the main loop of the program. This is where the magic happens, the main loop is the code which runs on a repeating cycle as long as the Arduino is powered on.

The first step is to read from the duty_cycle_in pin (A0) and store that value into the duty_cycle variable. Notice that I divide the result by 4, this has to do with a difference in resolution between the analog input pins and PWM output pins. the analogRead function returns a value between 0 and 1023 depending on where the voltage falls between 0V and 5V. Meanwhile the analogWrite takes a value between 0 (always off) and 255 (always on). To deal with this discrepancy we simply divide the input by 4 to bring it from 0-1023 down to 0-255.

Next we take that duty_cycle value and write it to the PWM_out pin using analogWrite. together these two lines mean the Arduino will be constantly checking the value at the potentiometer and writing that value to the PWM pin as a duty cycle (with an average voltage equal to the value read from the potentiometer).

Filtering PWM Signals

In a recent post I talked about how you can use Pulse Width Modulation to create a simple voltage controller. However PWM is only half the story. Once we have our PWM signal how do we transform this from a malformed square wave into a nice steady DC voltage? There are many different techniques that can be used to do this but today I’d like to introduce you to one of the simplest, Low Pass Filters.

Low Pass Filters

I briefly introduced RC low pass filters in my post on Square Waves in RC Circuits. Put simply these are circuits which allow low frequency signals to pass through while attenuating high frequency signals. The reason for this has to do with the capacitors charging. If you recall from my previous post the time a capacitor takes to charge in an RC circuit is approximately equal to 5 times the time constant of the circuit (RC). When the frequency is low enough that the capacitor has the chance to fully charge and discharge each cycle the signal will pass through. If however the capacitor cannot fully charge/discharge a certain amount of the current will always be passing through the capacitor to ground which attenuates the signal at the output. The higher the frequency the greater the attenuation.

The key understanding here is what happens to the signal when it is being attenuated. You might expect if you pass a 5V square wave (0-5V) through a filter which reduces the amplitude by 50% that the resulting 2.5V signal would be from 0-2.5V. However, this is not the case. Since the capacitor cannot fully charge or discharge the signal will stabilize at the average voltage of the incoming signal. In the case of this example the signal would travel between 1.25V and 3.75V. As we attenuate it further we can get a smaller and smaller peak to peak voltage (always centered around the average voltage). The smaller these peaks, the closer you get to your target DC voltage.

Ripple Vs Stabilization Time

So that all sounds great but how do we know what capacitance and resistance to use? This actually gets a bit more complicated. When choosing our resistors and capacitors we often find ourselves balancing two undesirable characteristics of the circuit.

Consider this first filter. Obviously this is a long way from a smooth DC voltage. There is a distinct ripple in the output with the voltage moving up and down in a sharp triangle pattern. As discussed earlier we should be able to reduce this ripple by increasing the time the capacitor takes to charge (increasing the resistance or capacitance) to further attenuate the signal. This will however unfortunately introduce a new problem.

Here we can see that by increasing the attenuation of the signal we are able to produce a much smoother output signal. The issue here is on the left side of the simulation output. Since the capacitor is only charging and discharging a small amount the signal takes significantly longer to stabilize at the average voltage.

Where on this spectrum your filter falls depends largely on your application. If you need a very stable signal which will not vary over time you can use a large capacitor and/or resistance. If on the other hand your signal strength needs to change quickly over time and your circuit can handle a bit more ripple you may opt for a smaller capacitor to support this behavior.

As you might imagine there are additions we can make to this circuit to improve both of these behaviors. By adding additional complexity to this filter we can develop a more robust digital to analog converter. I hope though that this has provided something of a starting point to begin generating analog signals from your digital devices.

Pulse Width Modulation

You may have encountered Pulse Width Modulation when working with Arduino or other microcontrollers. PWM is a powerful tool that is often implemented to control motors and dim LEDs in electronics projects. While it’s typical applications are not always audio-centric PWM can still be a useful tool in our tool belt. PWM can be used to modify the sound of our humble square wave oscillators and is foundational to many digital to analog converters.

Duty Cycle

The duty cycle of a square wave is the ratio of time the wave spends in its high state to the time it spends low. A perfect square wave would have a duty cycle of 50%. If you increase the time the wave spends high the duty cycle increases, if you decrease it the duty cycle decreases. A duty cycle of 100% would represent a DC voltage (at the output voltage of your source). Meanwhile a duty cycle of 0% would represent a steady 0V.

Below I have graphed some basic PWM signals (blue) along with their duty cycle and average voltage (orange):

50% Duty Cycle
75% Duty Cycle
25% Duty Cycle

Average Voltage

The key to understanding how to use PWM often lies in understanding average voltage. In the graph above you can see the average voltage (orange line) is highest when the duty cycle is high. This should make intuitive sense since with, for example, a 75% duty cycle the voltage is high for 75% of the time and 0V for 25% of the time. You can find the average voltage of any PWM signal by multiplying the duty cycle by the max voltage. In a 5V circuit for instance, with a 20% duty cycle, the average voltage would be 1V (5*0.2=1).

A Quick Word On Frequency

As you might guess the frequency of a PWM signal can be critical to your system design. In an audio oscillator the role of frequency is largely unchanged, The frequency will set the tone of your output while the pulse width will allow you to adjust the fullness of your sound.

When you are using PWM to create an analog signal things get a bit more complicated. Typically a specific frequency is chosen and the subsequent filters are designed based on it (I will go further into this process when I discuss filtering PWM signals in a future post) . In choosing this frequency we would be looking for a balance between speed and control. At faster frequencies it is easier to filter the signal (to obtain a steady voltage) and you can change the output voltage quicker. However, the faster the signal the harder it becomes to control the exact duty cycle. You want to maintain the fastest frequency possible where you can still adjust the duty cycle with the precision your application requires.

I hope this has given you a framework to begin working with PWM. Keep an eye out for my next post; I will be looking at filtering these PWM signals to obtain a steady voltage.

Square Waves In RC Circuits

Last week I introduced the Step Response in RC Circuits and we looked at a simple example of turning on a power switch. Today I’d like to extend this intuition to investigate the response of an RC circuit supplied with a square wave signal. This intuition forms the basis of understanding more complex concepts like filters and pulse width modulation.

Square Waves

We’ve used square waves quite a bit when working with simple oscillators. They are easy to understand and easy to create, but how do they relate to the step response?

A square wave can be visualized as nothing more than a series of steps. First stepping up to the high voltage mark, then after some time stepping back down. Consider our example from last week, If instead of turning the power on and leaving it, you turned it on, waited for a period, then turned it back off. Repeating this process over and over would produce a square wave. It follows that we should be able to apply our step equation to the steps in a square wave.

A quick word about pulse width: One way square waves can be manipulated is by adjusting the “Duty Cycle.” This means changing the ratio of how long the signal is high versus how long the signal is low. To keep things simple today we will work with a 50% duty cycle meaning the signal will be high for the the same period it is low.

Frequency vs Period

When working with synthesizers you’ve probably heard signals described in terms of frequency. The frequency of a sound wave (Or any wave for that matter) is the number of times the signal cycles (goes up and back down) in a second and is expressed in Hz. For these calculations we need a slightly different descriptor for the speed of the waves. By taking the inverse of the frequency (1/f) we can find the period. The period describes the time in seconds that the wave takes to cycle. In a square wave with a 50% duty cycle we know that a step will take place twice every period (once up and once down). Further, these steps are evenly spaced. They take place at t=np and t=p(n+1/2) (Where n is any whole number).

Time Constant

Relationship Between Capacitor Charging (5V circuit) and Time Constant

In my last post I introduced the time constant. In an RC circuit the time constant is defined as the product of the resistance and capacitance (RC). It is used to determine the speed at which a capacitor will fully charge or discharge. Note the time constant is the same for both charging and discharging.

The graph above shows the relationship between the charging/discharging of a capacitor and the time constant in a 5V circuit. Since this is an exponential equation the capacitor will never fully charge or discharge (in theory) however for calculations we say that the capacitor is fully charged after 5 time steps. This charge would represent 99.3% of the maximum value. This means if you had a time constant of 0.2 the capacitor would take 1s to fully charge.

Filter Circuit

Passive Low Pass Filter Circuit

To illustrate how this all comes together lets have a look at the low pass filter circuit above. Let’s pass a square wave at 1Hz (50% duty cycle) into this circuit and see what happens. The first thing we need is our time constant for this circuit:

So if our time constant is 0.1 we know that it will take 0.5s for the capacitor to fully charge or discharge (5*0.1). With our frequency of 1Hz we know that the square wave will cycle every 1s (1/1). The steps in the square wave will occur every 0.5s (switching between stepping up and stepping down). This means every step will happen exactly when the capacitor reaches full or zero charge. So what does that look like?

Effect Of Low Pass Filter on 1Hz Square Wave

Here we can see the charging and discharging cycles have turned our square wave into a sawtooth. This is only the beginning of what filters can do for us though.

The important question here is what would happen if we changed the frequency? If we doubled the frequency to 2Hz the period would become 0.5s (1/2). This means the steps would be occurring every 0.25s instead of every 0.5s. If we bring back the equation used in my last post we can see how much voltage would build across the capacitor in this time:

Here we can see that with a frequency of 2Hz the output voltage will only reach 4.59V before the input steps back down to 0V. This attenuation only gets worse as the frequency increases. At a frequency of 4Hz the peak voltage falls to 3.57V. At 8Hz you only see a peak voltage of 0.304V.

Note: This is a slight oversimplification, since we are shortening both the high and low periods. This means not only the charging but also the discharging state will be cut short. The capacitor will be unable to fully charge or discharge so the attenuated signal will stabilize at an offset from zero volts.

It is this attenuation that makes this a low pass filter. Low frequency signals (below a certain critical point) are able to pass at full amplitude while high frequency signals are attenuated or even eliminated from the output. We’ll explore filters further at a later date but this should give you some idea of the mechanisms which allow them to function.