0
0
AutocadHow-ToBeginner · 3 min read

How to Use analogWrite in Arduino: Simple Guide and Examples

Use analogWrite(pin, value) in Arduino to output a PWM signal on a pin, where pin is the pin number and value is a number from 0 (off) to 255 (fully on). This simulates an analog output by rapidly switching the pin on and off at different duty cycles.
📐

Syntax

The analogWrite() function sends a PWM signal to a specified pin. It takes two arguments:

  • pin: The Arduino pin number that supports PWM (usually marked with ~).
  • value: An integer from 0 to 255 representing the duty cycle (0 = always off, 255 = always on).

This function does not produce a true analog voltage but simulates it by switching the pin on and off very fast.

arduino
analogWrite(pin, value);
💻

Example

This example gradually increases and decreases the brightness of an LED connected to pin 9 using analogWrite(). It shows how PWM controls brightness by changing the duty cycle.

arduino
const int ledPin = 9;

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

void loop() {
  for (int brightness = 0; brightness <= 255; brightness++) {
    analogWrite(ledPin, brightness);
    delay(10);
  }
  for (int brightness = 255; brightness >= 0; brightness--) {
    analogWrite(ledPin, brightness);
    delay(10);
  }
}
Output
LED brightness smoothly increases from off to fully bright, then decreases back to off repeatedly.
⚠️

Common Pitfalls

  • Using analogWrite() on pins that do not support PWM will not work.
  • Passing values outside 0-255 will be ignored or cause unexpected behavior.
  • Expecting a true analog voltage output; analogWrite() only simulates analog by PWM.
  • Not setting the pin mode to OUTPUT before using analogWrite().
arduino
/* Wrong: Using analogWrite on pin 2 (no PWM) */
void setup() {
  pinMode(2, OUTPUT);
}
void loop() {
  analogWrite(2, 128); // Won't work as expected
  delay(1000);
}

/* Right: Using analogWrite on pin 9 (PWM pin) */
void setup() {
  pinMode(9, OUTPUT);
}
void loop() {
  analogWrite(9, 128); // Works correctly
  delay(1000);
}
📊

Quick Reference

analogWrite() Cheat Sheet:

ParameterDescriptionNotes
pinPin number to output PWMMust be PWM-capable (~ pins)
valuePWM duty cycle (0-255)0 = off, 255 = fully on
ReturnNoneFunction returns void
PWM FrequencyAbout 490 Hz (varies by board)Not adjustable by analogWrite()
Pin ModeMust be set to OUTPUTUse pinMode(pin, OUTPUT) before analogWrite()

Key Takeaways

Use analogWrite(pin, value) to output PWM signals on PWM-capable pins.
Value ranges from 0 (off) to 255 (fully on) controlling duty cycle.
analogWrite simulates analog output by fast switching, not true voltage.
Always set pinMode(pin, OUTPUT) before using analogWrite.
Check your board's PWM pins; using non-PWM pins will not work.