Learn electronics, coding, and projects — step by step.

Arduino Basics: Analog Output (PWM)

Table of Contents

Arduino boards cannot produce true analog voltages on their digital pins. Instead, they use PWM (Pulse Width Modulation) to simulate analog output. PWM rapidly switches a pin between HIGH and LOW, and the ratio of ON time to OFF time determines the effective voltage.

Using PWM with analogWrite()

  • analogWrite(pin, value) sets the PWM output on a pin.
  • value ranges from 0 (always LOW, 0V) to 255 (always HIGH, 5V).
  • Pins capable of PWM are marked with a ~ on most Arduino boards (e.g., ~3, ~5, ~6, ~9, ~10, ~11 on Arduino Uno).

Example 1: Dimming an LED

int ledPin = 9; // PWM-capable pin
int brightness = 0;
int fadeAmount = 5;

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

void loop() {
  analogWrite(ledPin, brightness); // Set LED brightness
  brightness = brightness + fadeAmount;

  // Reverse direction at limits
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }

  delay(30); // Small delay for smooth fading
}

Example 2: Controlling Motor Speed

int motorPin = 3; // PWM-capable pin
int speed = 128;    // Half speed (0–255)

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

void loop() {
  analogWrite(motorPin, speed); // Control motor speed
  // You can change 'speed' dynamically for acceleration
}

Tips for Using PWM

  • Use only PWM-capable pins for analogWrite.
  • For LEDs, PWM changes perceived brightness; for motors, it controls speed or power.
  • Combine PWM with smoothing circuits (capacitors) if a more stable analog voltage is needed.
  • Remember that analogWrite does not produce continuous voltage—it is a digital simulation.

By using PWM, you can add dynamic control to your projects, such as dimming lights, adjusting fan or motor speeds, and creating analog-like behaviors with digital pins.

×



Related Articles: (by Series)