Blog

PWM explained: how to control motor speed and LED brightness

Alessandro Panait·

A microcontroller pin can only be fully on (5V) or fully off (0V). So how do you run a motor at half speed? The answer is PWM: Pulse Width Modulation.

The idea

Switch the pin on and off hundreds or thousands of times per second. If it is on 50% of the time, the motor or LED behaves as if it received about half the voltage. The percentage of "on" time is called the duty cycle.

  • 0% duty: fully off.
  • 50% duty: half power.
  • 100% duty: fully on.

In code

On Arduino, use analogWrite on a PWM-capable pin (marked ~). The value goes from 0 to 255:

analogWrite(9, 128);   // about 50% power
analogWrite(9, 255);   // full power

Why it matters in robotics

  • Motor speed: a motor driver takes a PWM signal and adjusts how fast the wheels turn. This is how a robot slows down in a curve and speeds up on a straight.
  • LED brightness / lighting: dim your lights without extra hardware.
  • Servo control uses a special form of PWM to set an angle (more in the servo lesson).

One thing to watch

PWM controls average power, not torque directly. At very low duty cycles a motor may buzz without turning because it cannot overcome friction. That is normal: real robots keep a minimum useful speed rather than crawling at 5% power.

Comments (0)