What does analogWrite() do in Arduino?

 analogWrite() makes an Arduino pin output a PWM (pulse-width modulated) signal that behaves like an “analog” level to things like LEDs and DC motors.



What it actually does

  • Outputs a square wave that switches HIGH/LOW quickly.

  • You set a value (usually 0–255) that controls the duty cycle (how long it stays HIGH each cycle).

    • analogWrite(pin, 0) → always OFF (0% duty)

    • analogWrite(pin, 255) → always ON (100% duty)

    • analogWrite(pin, 128) → ~50% duty

What it’s used for

  • LED dimming (brightness follows duty cycle)

  • Motor speed control (with a driver/MOSFET)

  • Generating a basic PWM control signal (e.g., for some devices)

Important notes

  • It only works on PWM-capable pins (marked with ~ on many boards).

  • It does not output a true analog voltage by itself.
    If you want a real DC voltage, you need:

    • a low-pass RC filter, or

    • a DAC pin (some boards like Due/Zero have DAC), or

    • an external DAC.

PWM frequency depends on the board

  • Uno/Nano (ATmega328P): typically ~490 Hz on most PWM pins, ~980 Hz on a couple pins (because different timers).

  • Other boards (Mega, Leonardo, SAMD, etc.) can differ.

Tiny example

int led = 9; // PWM pin void setup() { pinMode(led, OUTPUT); } void loop() { analogWrite(led, 64); // ~25% brightness delay(1000); analogWrite(led, 192); // ~75% brightness delay(1000); }

评论

此博客中的热门博文

Detailed Explanation of STM32 HAL Library Clock System

How To Connect Stm32 To PC?

How do you set up ADC (Analog-to-Digital Converter) in STM32?