पाठ 8 / 25

PWM with analogWrite

Duty cycle, dimming and speed control.

Duty cycle

Most MCUs cannot output a true analog voltage on ordinary pins. Pulse-width modulation (PWM) switches a pin on and off rapidly; the fraction of time it is HIGH is the duty cycle. An LED or motor averages these pulses, so 25 % duty looks dim and 100 % is full on. analogWrite(pin, value) takes 0 to 255 by default. On the Uno R3 only pins marked with ~ (3, 5, 6, 9, 10, 11) support it, at roughly 490 Hz (about 980 Hz on pins 5 and 6). Other boards have different PWM pins and frequencies, and some ESP32 core versions use the LEDC peripheral underneath; check your board's pinout and core documentation.

Fade an LED in and out

Uno R3: LED with 330 Ω resistor on PWM pin 9.

const uint8_t LED_PIN = 9;   // must be a PWM-capable pin
int level = 0, step = 5;
unsigned long last = 0;

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

void loop() {
  if (millis() - last >= 20) {
    last = millis();
    analogWrite(LED_PIN, level);        // 0 = off, 255 = fully on
    level += step;
    if (level <= 0 || level >= 255) step = -step;
  }
}

Flicking a light switch very fast

PWM is like flicking a light switch so quickly that your eye only sees the average brightness; leaving it on longer each cycle makes the room look brighter.

त्वरित जाँच: What does analogWrite(pin, 64) roughly produce on an Uno R3 PWM pin?

  • A 64 Hz sine wave
  • A steady 1.25 V DC voltage
  • A square wave HIGH about 25 % of the time
  • Nothing, because analogWrite is for inputs
Answer

A square wave HIGH about 25 % of the time — 64/255 is about a quarter duty cycle.