Home ▸ Arduino ▸ Core Tutorials ▸ PWM & analogWrite()

Arduino PWM and analogWrite(): Duty Cycle, Frequency and Examples

The analogWrite() function does not produce a true analog voltage. It switches a digital pin on and off very quickly, and the connected device reacts to the average of those pulses. This technique is called PWM (pulse width modulation), and it is the standard way to dim an LED, control the speed of a motor or generate a simple tone with nothing more than a digital pin.

This guide explains how PWM works and how the duty cycle and the frequency affect the output. It lists the PWM pins of the common Arduino boards, shows how to use analogWrite() for LED brightness and motor speed, and explains how to change the PWM frequency with the timer registers. A section on custom frequencies with Timer1, a short ESP32 example and a troubleshooting section for the most common PWM problems complete the guide.

This tutorial is part of the Arduino Core tutorials. If you are new to Arduino input and output, the digitalWrite() and digitalRead() tutorial and the Arduino UNO pinout guide are good starting points. The analogRead() and ADC tutorial covers the opposite direction, which is reading analog signals.

Arduino PWM Basics

A digital pin can only be HIGH (5 V) or LOW (0 V), so it cannot output 2.5 V or 3.3 V directly. PWM solves this by switching the pin on and off thousands of times per second. The connected device cannot follow such fast changes, so it responds to the average value, and the share of time that the pin spends HIGH decides how strong that average is.

Duty Cycle

The duty cycle is the percentage of each cycle in which the pin is HIGH.

  • A duty cycle of 0 percent keeps the pin LOW all the time, so the average voltage is 0 V.
  • A duty cycle of 50 percent keeps the pin HIGH for half of each cycle, so the average voltage is 2.5 V.
  • A duty cycle of 100 percent keeps the pin HIGH all the time, so the average voltage is 5 V.

The average output voltage follows a simple formula.

Average voltage = (duty cycle / 100) × supply voltage

At a supply of 5 V and a duty cycle of 75 percent, the average voltage is 0.75 × 5 V = 3.75 V.

Arduino PWM waveform showing 25%, 50%, and 75% duty cycles and their effect on average output voltage

Frequency

The frequency is the number of on-and-off cycles per second, measured in hertz (Hz). On the Arduino Uno and Nano, most PWM pins run at about 490 Hz, and pins 5 and 6 run at about 980 Hz. These speeds are high enough that an LED shows no visible flicker and a small motor reacts only to the average power. The duty cycle controls how strong the output is, and the frequency controls how smooth it looks or sounds.

PWM suits loads that respond to the average, such as LEDs, heaters and motors. It is not a clean analog signal, so it is a poor choice for a circuit that needs a steady DC voltage, unless a filter smooths the pulses. The FAQ at the end shows a simple filter.


Arduino PWM Pins

PWM comes from the hardware timers inside the microcontroller, so only the pins that connect to a timer can use analogWrite(). On most boards, the PWM pins carry a tilde (~) next to the pin number.

BoardPWM pins
Uno, Nano and Pro Mini3, 5, 6, 9, 10, 11
Mega 25602 to 13 and 44 to 46
Leonardo and Micro3, 5, 6, 9, 10, 11, 13
Due2 to 13, plus true analog output on DAC0 and DAC1
ESP32Almost any output pin, through the LEDC module

Calling analogWrite() on a pin without PWM support does not produce a PWM signal. On the AVR boards, the pin simply goes HIGH for values of 128 and above and LOW for lower values. The Arduino UNO pinout guide and the Arduino Nano pinout guide show the PWM pins and the timer behind each one.

Arduino Uno digital header with the PWM pins 3, 5, 6, 9, 10 and 11 marked with a tilde

PWM Pins and Timers on the Uno

PinTimerDefault frequency
3 and 11Timer2about 490 Hz
5 and 6Timer0about 980 Hz
9 and 10Timer1about 490 Hz

Several other functions share these timers. Timer0 also drives millis() and delay(), Timer1 is used by the Servo library, and Timer2 is used by tone(). The troubleshooting section explains the conflicts that follow from this.

Plan the pins of a project before you wire it. The SPI bus uses pins 11 and 13, and pin 10 is the usual chip select, so a project with an SPI display has fewer free PWM pins than the table suggests.


Arduino analogWrite() Function

The analogWrite() function sets the duty cycle of the PWM signal on a supported pin. It configures the timer by itself, so no extra setup is needed.

analogWrite(pin, value);
  • pin is the number of a PWM-capable pin.
  • value is the duty cycle from 0 (always LOW) to 255 (always HIGH).
ValueDuty cycleAverage voltage on a 5 V board
00 percent0 V
64about 25 percentabout 1.25 V
128about 50 percentabout 2.5 V
192about 75 percentabout 3.75 V
255100 percent5 V

The duty cycle in percent is the value divided by 255 and multiplied by 100.

The call pinMode(pin, OUTPUT) is not required before analogWrite(), because the function sets the pin mode itself. It is still a good habit, since it shows the reader of your code that the pin is an output.

Resolution and Default Frequency

The AVR boards have an 8-bit PWM resolution, which gives 256 steps from 0 to 255. The Due, the Zero and the ESP32 can use a higher resolution, and the ESP32 section below shows how. The default frequencies on the Uno and the Nano are about 490 Hz on pins 3, 9, 10 and 11, and about 980 Hz on pins 5 and 6. The exact values are 490.2 Hz and 976.6 Hz, which the Arduino documentation rounds.


analogWrite() and digitalWrite() on the Same Pin

You can use both functions on the same pin. A call to digitalWrite() on a PWM pin turns the PWM off and sets the pin to a fixed HIGH or LOW level. A call to analogWrite(pin, 0) or analogWrite(pin, 255) behaves in the same way, and it sets the pin to a fixed level without PWM.


Arduino PWM LED Brightness

Dimming an LED is the classic first PWM project. Connect the anode of an LED through a resistor of 220 Ω to pin 9 and the cathode to GND. The sketch below fades the LED from off to full brightness and back.

const int ledPin = 9;   // PWM pin connected to the LED

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  for (int brightness = 0; brightness <= 255; brightness++) {
    analogWrite(ledPin, brightness);   // Fade in
    delay(10);
  }

  for (int brightness = 255; brightness >= 0; brightness--) {
    analogWrite(ledPin, brightness);   // Fade out
    delay(10);
  }
}

Each step raises the duty cycle by about 0.4 percent, which is one part in 255. With a delay of 10 ms per step, a full fade in one direction takes 2.55 seconds.

Oscilloscope capture of the PWM duty cycle on pin 9 rising from 0 to 100 percent while the LED fades in and out

The oscilloscope shows the duty cycle rising and falling as the sketch runs, and a voltmeter on pin 9 follows the average voltage from 0 V to 5 V.

Fade Without delay()

The delay() function blocks the sketch, so nothing else can run during the fade. A version with millis() updates the brightness at fixed intervals and leaves the loop free for other work.

const int ledPin = 9;
int brightness = 0;
int step = 5;
unsigned long lastUpdate = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (millis() - lastUpdate >= 30) {
    lastUpdate = millis();

    analogWrite(ledPin, brightness);

    brightness += step;
    if (brightness <= 0 || brightness >= 255) {
      brightness = constrain(brightness, 0, 255);
      step = -step;                    // Reverse the direction at both ends
    }
  }
}

The FreeRTOS timing tutorial shows another way to run an LED fade next to other tasks.


Control the Brightness with a Potentiometer

The ADC reads a value from 0 to 1023, and analogWrite() accepts 0 to 255, so the map() function connects the two. Connect the middle pin of a potentiometer to A0 and its outer pins to 5 V and GND.

const int ledPin = 9;
const int potPin = A0;

void loop() {
  int reading = analogRead(potPin);                // 0 to 1023
  int level = map(reading, 0, 1023, 0, 255);       // 0 to 255
  analogWrite(ledPin, level);
}

The analogRead() and ADC tutorial explains the reading side in detail.


Gamma Correction for Natural Dimming

The human eye does not see brightness in a linear way. A duty cycle of 50 percent looks much brighter than half of the full brightness, so most of the visible change happens at the low end of the range. A gamma correction compensates for this, and a fade then looks even from start to finish.

uint8_t gamma8(uint8_t level) {
  return (uint8_t)(pow(level / 255.0, 2.2) * 255.0 + 0.5);
}

// Use it in the fade loop
analogWrite(ledPin, gamma8(brightness));

The exponent of 2.2 is a common starting value, and you can adjust it to taste.

PWM is also useful for larger LED projects. The PIR sensor tutorial builds a smart light that can use a PWM fade, and the ST7735 tutorial uses PWM to dim a display backlight.


Arduino PWM Motor Speed Control

A DC motor draws far more current than an Arduino pin can supply, so never connect a motor directly to a pin. Use a motor driver, such as an L298N or an L293D, or a logic-level MOSFET, and feed the PWM signal to the input of the driver. The motor gets its own supply, and the grounds of the supply and the Arduino must be connected.

The sketch below uses an L298N module. The PWM pin 5 drives the ENA input, and the pins 7 and 8 set the direction. Remove the jumper from the ENA pin of the module first, so that the Arduino controls the enable input.

const int enablePin = 5;   // PWM pin connected to ENA
const int in1 = 7;         // Direction pins
const int in2 = 8;

void setup() {
  pinMode(enablePin, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  digitalWrite(in1, HIGH);   // Forward direction
  digitalWrite(in2, LOW);
}

void loop() {
  analogWrite(enablePin, 128);   // About 50 percent duty cycle, half speed
  delay(2000);

  analogWrite(enablePin, 255);   // 100 percent duty cycle, full speed
  delay(2000);

  analogWrite(enablePin, 0);     // 0 percent duty cycle, stop
  delay(2000);
}

The driver turns the PWM signal into a proportional motor current, so a higher duty cycle gives a higher average voltage and a higher speed.

Oscilloscope capture of PWM on pin 5 at 50 percent, 100 percent and 0 percent duty cycle with the motor speed changing

Motor Control Notes

  • A motor often does not start at a low duty cycle, because it needs a minimum voltage to overcome friction. Test your motor and avoid values below its start threshold.
  • When you drive an inductive load with a MOSFET, add a flyback diode across the load to protect the transistor from voltage spikes. A resistor of 100 Ω to 220 Ω between the Arduino pin and the gate limits the switching current.
  • Pin 5 runs at about 980 Hz. This is audible as a whine, and the next sections show how to raise the frequency.

Arduino PWM Frequency

The default frequencies suit most projects, but a few situations call for a change.

  • A visible LED flicker, especially in camera footage, means that the frequency is too low. Raise it above 1 kHz.
  • A motor that whines or buzzes needs a frequency above about 20 kHz, which is beyond normal hearing.
  • A project that needs a specific signal frequency, such as a servo signal or an audio tone, needs a precise setting.

The frequency comes from the timer. A prescaler divides the 16 MHz system clock before it reaches the timer, and a smaller prescaler gives a higher PWM frequency. Two methods change it. The first one edits the prescaler bits in the timer registers and keeps analogWrite() for the duty cycle. The second one configures Timer1 directly for a free choice of frequency.

A higher frequency also has costs. Some motor drivers, such as the L298N and the L293D, are not designed for frequencies above a few kilohertz, so they run hot or lose power at 31 kHz. Check the datasheet of the driver. A logic-level MOSFET or a modern motor driver handles high frequencies much better.


Arduino PWM Timer Registers

Each timer has a control register, TCCRnB, whose lowest three bits select the prescaler. The code below clears those three bits and writes a new value, and it leaves the other bits of the register unchanged.

Timer1 on Pins 9 and 10

Timer1 works in phase-correct PWM mode in the Arduino core, and its frequency is 16 MHz divided by the prescaler and by 510.

// Timer1 changes pins 9 and 10
TCCR1B = (TCCR1B & 0b11111000) | 0x01;   // Prescaler 1, about 31.4 kHz
TCCR1B valuePrescalerPWM frequency
0x011about 31.4 kHz
0x028about 3.9 kHz
0x0364about 490 Hz (default)
0x04256about 122 Hz
0x051024about 30.6 Hz

Timer2 on Pins 3 and 11

Timer2 also uses phase-correct PWM, so the frequency is again 16 MHz divided by the prescaler and by 510. It has more prescaler options than the other timers.

// Timer2 changes pins 3 and 11
TCCR2B = (TCCR2B & 0b11111000) | 0x01;   // Prescaler 1, about 31.4 kHz
TCCR2B valuePrescalerPWM frequency
0x011about 31.4 kHz
0x028about 3.9 kHz
0x0332about 980 Hz
0x0464about 490 Hz (default)
0x05128about 245 Hz
0x06256about 122 Hz
0x071024about 30.6 Hz

Timer0 on Pins 5 and 6

Timer0 uses fast PWM, so its frequency is 16 MHz divided by the prescaler and by 256.

// Timer0 changes pins 5 and 6, and it also changes millis() and delay()
TCCR0B = (TCCR0B & 0b11111000) | 0x02;   // Prescaler 8, about 7.8 kHz
TCCR0B valuePrescalerPWM frequency
0x011about 62.5 kHz
0x028about 7.8 kHz
0x0364about 976 Hz (default)
0x04256about 244 Hz
0x051024about 61 Hz

Timer0 also drives millis(), micros() and delay(), so a new prescaler changes the speed of all of them. With a prescaler of 8, the time functions run eight times too fast, and delay(1000) lasts only about 125 ms. Use Timer1 or Timer2 for a frequency change whenever you can. If you must change Timer0, scale your delays by the same factor.

After you change a prescaler, analogWrite() still sets the duty cycle in the usual way. The change affects both pins of the timer, so two pins that share a timer always run at the same frequency.


Arduino PWM Custom Frequency with Timer1

The prescaler method gives only a few fixed frequencies. For an exact frequency, configure Timer1 directly in fast PWM mode with the register ICR1 as the TOP value. The timer counts from 0 to ICR1, and the period of the signal is one more than that count.

Frequency = 16,000,000 / (prescaler × (ICR1 + 1))
Duty cycle = OCR1A / (ICR1 + 1)

The sketch below creates a 40 kHz signal with a 50 percent duty cycle on pin 9.

void setup() {
  pinMode(9, OUTPUT);

  // Fast PWM (mode 14), ICR1 as TOP, non-inverting output on pin 9, prescaler 1
  TCCR1A = (1 << COM1A1) | (1 << WGM11);
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);

  ICR1  = 399;    // 16,000,000 / (1 × 400) = 40 kHz
  OCR1A = 200;    // 200 / 400 = 50 percent duty cycle
}

void loop() {
}

The value of ICR1 sets the frequency, and the value of OCR1A sets the duty cycle. The same configuration can drive pin 10 with the register OCR1B, if you add the bit COM1B1 to TCCR1A.

A Helper Function for Any Frequency

A small function can compute the register values for a frequency and a duty cycle in percent.

void setPwm(unsigned long frequency, float dutyPercent) {
  ICR1  = F_CPU / frequency - 1;               // TOP value, prescaler 1
  OCR1A = (ICR1 + 1) * dutyPercent / 100.0;    // Compare value
}

// Example: 25 kHz with a 30 percent duty cycle
// setPwm(25000, 30.0);

With a prescaler of 1, this works for frequencies of about 245 Hz and above, because ICR1 holds at most 65,535.


Frequency and Resolution

The number of steps in the duty cycle is ICR1 + 1, so a higher frequency leaves fewer steps. At 40 kHz, the duty cycle has 400 steps, which is a little more than 8 bits. At 1 kHz, it has 16,000 steps, which is almost 14 bits. This trade-off holds for every timer: the frequency multiplied by the number of steps cannot exceed 16 MHz.

Timer1 is used for this setup, so the Servo library and analogWrite() on pins 9 and 10 can no longer be used together with it. A call of analogWrite() on these pins would write values in the range of 0 to 255 into a timer that now counts to a different TOP value.


ESP32 PWM with LEDC

The ESP32 generates PWM with the LEDC module, which lets you choose the frequency and the resolution for each channel. It offers more freedom than the AVR timers, and most output pins can carry a PWM signal. The function names depend on the version of the ESP32 Arduino core, so check the version in the Boards Manager before you copy a sketch.

ESP32 Arduino Core 3.x

Version 3.0 and later attach a pin to the LEDC module with a single call and write the duty cycle to the pin itself.

const int ledPin = 5;
const int freq = 5000;        // 5 kHz
const int resolution = 8;     // 8 bits, duty values from 0 to 255

void setup() {
  ledcAttach(ledPin, freq, resolution);
}

void loop() {
  for (int duty = 0; duty <= 255; duty++) {
    ledcWrite(ledPin, duty);
    delay(10);
  }
}

ESP32 Arduino Core 2.x

Older versions use a channel number, which you configure first and then attach to the pin.

const int ledPin = 5;
const int channel = 0;
const int freq = 5000;
const int resolution = 8;

void setup() {
  ledcSetup(channel, freq, resolution);
  ledcAttachPin(ledPin, channel);
}

void loop() {
  for (int duty = 0; duty <= 255; duty++) {
    ledcWrite(channel, duty);
    delay(10);
  }
}

In both versions, the resolution decides the maximum duty value, which is 2 to the power of the resolution minus 1. A resolution of 10 bits gives duty values from 0 to 1023. The ESP32 core tutorials cover this platform in more detail.


Arduino PWM Troubleshooting

Most PWM problems come from the pin choice, a timer conflict or a frequency that does not suit the load.

analogWrite() Has No Effect

The pin probably does not support PWM. Use a pin with a tilde (~). If the pin is correct, a library may have taken over its timer. The Servo library takes Timer1, and tone() takes Timer2, so move to a pin on a different timer.


PWM Stops Working After tone()

The tone() function uses Timer2 on the Uno, so PWM on pins 3 and 11 stops while a tone plays and may not return to its old frequency. Use pins 5, 6, 9 or 10 for PWM in a sketch that also plays tones. The passive buzzer tutorial shows the sound side of this conflict.


The LED Flickers

The PWM frequency may be too low for your eyes or for a camera. Raise it above 1 kHz with a Timer1 or Timer2 prescaler. Pins 5 and 6 run at about 980 Hz and are usually free of visible flicker, while the pins at 490 Hz can show a flicker in some conditions.


The LED Looks Fully Bright Long Before 255

The eye sees brightness in a nonlinear way, so most of the visible change happens at low duty cycles. Apply the gamma correction from the LED section to get an even fade.


The Motor Whines or Buzzes

The default 490 Hz and 980 Hz are inside the audible range, and the coils of the motor vibrate at the PWM frequency. Move the signal to a pin on Timer1 or Timer2 and set the prescaler to 1, which gives about 31 kHz. Check that your motor driver can handle this frequency.


The Motor Does Not Start at Low Values

A DC motor needs a minimum average voltage to overcome friction, so it stays still at low duty cycles. Find the lowest value at which your motor starts, and keep the PWM value above that when the motor should run.


millis() or delay() Stopped Working

You changed the Timer0 prescaler. Timer0 drives all Arduino timekeeping functions. Restore the default value to fix it.

TCCR0B = (TCCR0B & 0b11111000) | 0x03;   // Default Timer0 prescaler of 64

A Servo Jitters After You Add analogWrite()

The Servo library uses Timer1 on the Uno and disables PWM on pins 9 and 10. Use pins 3, 5, 6 or 11 for analogWrite() when a servo is active.


PWM Does Not Work on the Display Pins

The SPI bus uses pins 11 and 13, and the usual chip select is pin 10. When a TFT or SD card uses SPI, these pins are not free for PWM. The ILI9341 tutorial and the ST7735 tutorial show a free-pin layout for the backlight.


Conclusion

PWM controls an output by changing how long a digital pin stays HIGH in each cycle, and analogWrite() handles the hardware timers for you. The main points of this guide are the 8-bit duty cycle from 0 to 255, the default frequencies of about 490 Hz and 980 Hz, the three timers that decide which pins share a frequency and the fact that Timer0 also drives millis() and delay(). For a different frequency, change the prescaler of Timer1 or Timer2, or configure Timer1 directly for an exact value.

The next topic depends on your project. To read analog signals, continue with the analogRead() and ADC tutorial. To react to a button press without blocking, continue with the external interrupts tutorial. To send commands to the Arduino from a computer, for example to set a brightness value, continue with the Arduino UART tutorial.


Browse More Arduino Core Tutorials

About the Author
Arun Rawat
Arun Rawat
Embedded Systems Engineer · Founder, ControllersTech

Arun is an embedded systems engineer with 10+ years of experience in STM32, ESP32, and AVR microcontrollers. He created ControllersTech to share practical tutorials on embedded software, HAL drivers, RTOS, and hardware design — grounded in real industrial automation experience.

Subscribe
Notify of

0 Comments
Newest
Oldest Most Voted
×

Don’t Miss Future STM32 Tutorials

Join thousands of developers getting free guides, code examples, and updates.