Sub topic 12
Limits of PWM and Driving Larger Loads
This chapter assumes you can already wire an LED with a resistor to a PWM pin and call analogWrite(). It also assumes you know what duty cycle and PWM frequency mean, and that you have used Ohm's law to size a resistor. Here we look at where PWM stops working well and what to do about it. The topics are flicker, coarse brightness steps, pin current limits, and loads that need more power than a pin can supply.
PWM Is Not True Analog Output
PWM does not produce an in-between voltage. The pin is always either at 0 V or at 5 V. The "average" only exists if something downstream smooths the pulses. For an LED, your eye and the LED's light output do the smoothing. For other loads, the smoothing may be weak, absent, or harmful.
Three limits follow from this:
- Frequency. Pulses that are too slow are visible, audible, or picked up by cameras.
- Resolution.
analogWrite()gives 256 duty steps, which is coarse at the dim end. - Power. The pin only switches its own small output current. It cannot supply a motor or a LED strip.
Flicker and Frequency
On an Uno, analogWrite() runs at about 490 Hz on pins 3, 9, 10, and 11, and about 980 Hz on pins 5 and 6. These values come from the hardware timers (see the previous chapter). For a direct-view LED, both are well above the point where most people see flicker.
Flicker still shows up in some situations:
- Cameras. A phone camera with a rolling shutter reads the image line by line. Bright and dark bands then appear across a PWM-dimmed LED, even though your eye sees steady light.
- Fast eye movement. If you move your eyes or the LED quickly, the pulses smear into a dotted trail (the stroboscopic effect). This is most visible at low duty cycles, where the LED is on for a very short time.
- Peripheral vision. The eye is more sensitive to flicker at the edge of the visual field than at the center.
- Motors and coils. A motor or solenoid driven at 490 Hz can whine at that pitch, because the frequency is in the audible range.
The fix for all of these is a higher PWM frequency.
Changing the Frequency on an Uno
On the ATmega328P, the frequency of pins 9 and 10 depends on the prescaler of Timer1. The prescaler is a divider between the 16 MHz system clock and the timer. The Arduino core configures Timer1 for 8-bit phase-correct PWM, so the frequency is 16,000,000 / (510 × prescaler).
| Prescaler | Frequency (pins 9 and 10) |
|---|---|
| 1 | about 31.4 kHz |
| 8 | about 3.9 kHz |
| 64 (default) | about 490 Hz |
| 256 | about 122 Hz |
| 1024 | about 30.6 Hz |
The prescaler is selected by the lowest three bits of the TCCR1B register. This sketch raises pins 9 and 10 to about 31 kHz and holds the LED at roughly a quarter brightness:
const uint8_t LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
// Clear the three clock-select bits, then set 0b001 (no prescaling).
TCCR1B = (TCCR1B & 0b11111000) | 0b001;
}
void loop() {
analogWrite(LED_PIN, 64);
}This code works on the Uno and other ATmega328P boards only. Other boards use different registers.
A higher frequency is not always better. Each switching edge costs a little energy in the switching transistor, so a MOSFET dissipates more heat at 31 kHz than at 490 Hz. Some LED drivers and motor drivers also have a maximum input frequency. Check the datasheet.
Getting a Real Analog Voltage
If a circuit needs a smooth DC voltage rather than a pulse train, add a low-pass filter. A resistor in series with the signal and a capacitor from the output to ground is enough. With R = 1 kΩ and C = 10 µF, the cutoff frequency is 1 / (2π × R × C), about 16 Hz. A 490 Hz PWM signal is then reduced to a small ripple on top of the average level.
The filter has costs. The output responds slowly to duty changes, with a time constant R × C of 10 ms in this case. It also cannot supply much current without the voltage dropping, because the resistor is in series with the load. Use a buffer such as an op-amp if the load draws current. For a dedicated analog output, a DAC chip is usually the better choice.
Resolution at the Dim End
analogWrite() has 256 levels, and they are linear in duty cycle, not in perceived brightness. At the low end, each step is a large relative change. Going from 1 to 2 doubles the duty cycle (1/255 to 2/255). Going from 200 to 201 changes it by half a percent. A slow fade therefore looks smooth near the top and jumpy near the bottom.
Gamma correction makes this worse in one specific way. The gammaCorrect() function from the earlier chapter, with a gamma of 2.2, rounds the first 15 input levels (0 to 14) to an output of 0. The LED stays off for that part of the fade, and then jumps to the first lit step. You can see this as a delay at the start of every fade-up.
You have three ways to deal with this:
- Accept it for status lights and indicators, where nobody will notice.
- Raise the resolution with Timer1. Timer1 is a 16-bit timer. You can configure it for 10-bit or higher PWM by writing its registers directly, or you can use a library such as TimerOne. The cost is a lower frequency. The frequency is the clock divided by the number of counts, so each extra bit of resolution halves the frequency unless you also raise the clock.
- Use an external driver. The PCA9685 is a 16-channel I2C PWM chip with 12-bit resolution (4096 steps). It has its own oscillator, so it generates PWM without using any of the Uno's timers. It is also a good choice when you need more channels than the Uno has PWM pins.
Another technique is temporal dithering: alternate between two neighboring levels over time so the average falls between them. It needs a fast update loop and adds its own flicker, so it is mostly used in LED drivers rather than in simple sketches.
Pin Current Limits
An Uno pin is designed to supply a few LEDs, not a load. The ATmega328P datasheet gives these limits:
| Limit | Value |
|---|---|
| Recommended per pin | 20 mA |
| Absolute maximum per pin | 40 mA |
| Total across all pins | 200 mA |
A single LED with a resistor draws 10 to 20 mA, so it is fine. Several LEDs in parallel on one pin, a motor, a relay coil, or an LED strip are not. Exceeding the absolute maximum can damage the pin or the chip.
The rule for larger loads is that the Arduino pin carries only the control signal. A transistor switches the load current, and a separate power supply provides that current.
Switching Larger Loads with a MOSFET
A MOSFET is a voltage-controlled switch. A voltage at the gate pin turns the path between the drain and source on, and almost no current flows into the gate itself. That makes it a good match for a PWM pin, as long as you pick the right type.
For a 5 V Arduino, use a logic-level N-channel MOSFET. This type turns on fully at a gate voltage of 4.5 V or less. Examples are the IRLZ44N and the FQP30N06L. A general-purpose MOSFET such as the IRF540 needs about 10 V on the gate to be fully on. At 5 V it stays partly on, has high resistance, and overheats.
The usual circuit for a low-side switch is:
- Connect the Arduino PWM pin to the gate through a resistor of about 100 to 220 Ω. This limits the surge when the gate capacitance charges.
- Connect a 10 kΩ resistor from the gate to ground. It keeps the MOSFET off while the pin is floating, for example during boot.
- Connect the source to ground.
- Connect the load between the external supply's positive terminal and the drain.
- Connect the external supply's ground to the Arduino ground. Without a common ground, the gate voltage has no reference and the circuit does not work.
The sketch is the same as a plain LED fade. Only the wiring is different:
const uint8_t GATE_PIN = 9; // drives the MOSFET gate through a resistor
void setup() {
pinMode(GATE_PIN, OUTPUT);
}
void loop() {
for (int duty = 0; duty <= 255; duty++) {
analogWrite(GATE_PIN, duty);
delay(10);
}
for (int duty = 255; duty >= 0; duty--) {
analogWrite(GATE_PIN, duty);
delay(10);
}
}This works well for a 12 V constant-voltage LED strip, for example. Check the MOSFET's maximum drain current and its on-resistance. At 5 A with an on-resistance of 0.03 Ω, the MOSFET dissipates P = I² × R = 25 × 0.03 = 0.75 W. That is warm, and a heat sink may be needed.
Load Types and What Each Needs
Not every load tolerates PWM, and some need extra parts.
| Load | PWM suitable? | What to add |
|---|---|---|
| Single LED | Yes | Series resistor |
| Constant-voltage LED strip | Yes | Logic-level MOSFET, external supply |
| Constant-current LED driver | Only through its dimming input | Do not switch its power with PWM |
| DC motor | Yes | MOSFET, flyback diode, external supply |
| Solenoid or relay coil | Rarely | Flyback diode; relays wear out and chatter |
| Heater element | Yes, at a slow rate | MOSFET or solid-state relay rated for the load |
| Hobby servo | No | Uses its own pulse signal, not analogWrite() |
| Mains AC lamp | No | Needs a zero-cross dimmer circuit |
Inductive loads (motors, relays, solenoids) store energy in their coil. When the MOSFET turns off, the coil pushes current in the same direction and the voltage at the drain spikes far above the supply. This can destroy the MOSFET and send noise into the Arduino. A flyback diode across the load, with the stripe (cathode) toward the positive supply, gives that current a path to flow and absorbs the spike. A 1N4007 or a Schottky diode such as the 1N5819 works for small motors.
Servos also deserve a note. A hobby servo reads the width of a pulse sent every 20 ms, so it looks like PWM, but the pulse width encodes an angle, not a power level. Use the Servo library for it and not analogWrite().
Choosing an Approach
This diagram summarizes the decisions from this chapter:
Common Errors
- MOSFET gets hot and the load is dim. The MOSFET is not logic-level, so it is only partly on at 5 V. Replace it with a logic-level part.
- Nothing happens, but the wiring looks right. The external supply's ground is not connected to the Arduino ground.
- Load is on at power-up. The gate has no pull-down resistor, so it floats.
- Arduino resets when a motor starts. The motor's current spike or voltage spike disturbs the shared supply. Use a separate supply for the motor, add the flyback diode, and put a capacitor of 100 µF across the motor supply.
- Servo stops working after changing frequencies. Both use Timer1. Choose a different pin and timer, or do not change the prescaler.
- delay() or millis() runs at the wrong speed. You changed the Timer0 prescaler. Undo the change.
- PWM on pins 5 and 6 never goes fully dark at low values. These pins use a different PWM mode, so very low duty values give a slightly longer pulse than the value suggests. Use pins 9, 10, 3, or 11 if low-end accuracy matters.
Exercise
A 12 V LED strip draws 3 A at full brightness. You plan to connect it through an IRF540 MOSFET to Uno pin 9. What are two things wrong with this plan, and what do you change?
Show answer
First, the strip draws far more than the pin's 20 mA recommended limit, so it must not be connected to the pin directly. It has to be switched by the MOSFET, with the 12 V coming from an external supply. Second, the IRF540 is not a logic-level MOSFET. It needs about 10 V on the gate, and a 5 V pin leaves it partly on, so it will overheat and the strip will be dim. Replace it with a logic-level part such as the IRLZ44N. Also connect the supply ground to the Arduino ground, add a 100 to 220 ohm gate resistor, and add a 10 kilohm pull-down from gate to ground.
Exercise
You set TCCR1B = (TCCR1B & 0b11111000) | 0b010 on an Uno, which selects a prescaler of 8. What PWM frequency do pins 9 and 10 now have, and why is it a poor idea to make the same kind of change to Timer0?
Show answer
The frequency is 16,000,000 / (510 x 8), about 3.9 kHz. Timer0 drives millis(), micros(), and delay(), so changing its prescaler makes every timing function run at the wrong speed and breaks the fade and any other timed code. It also changes the frequency of pins 5 and 6.
Exercise
A gamma-corrected fade with gamma 2.2 stays dark for the first part of every fade-up. Roughly how many input levels map to an output of 0, and name two ways to reduce the effect.
Show answer
About 15 input levels (0 to 14) round to 0 with a gamma of 2.2 and the 8-bit output range. To reduce it, you can use a higher-resolution PWM setup on Timer1 so the low end has more steps, or use an external 12-bit PWM driver such as the PCA9685. A third option is to skip the dead zone by starting the visible fade at the first level that produces an output of 1.