Bird
0
0
Arduinoprogramming~5 mins

Motor speed control with PWM in Arduino

Choose your learning style9 modes available
Introduction

We use PWM to control how fast a motor spins by changing the power it gets. This helps save energy and makes the motor work just right.

When you want to make a fan spin slower or faster.
When controlling the speed of a toy car motor.
When adjusting the brightness of a motor-driven light.
When you need smooth speed changes in a robot's wheels.
Syntax
Arduino
analogWrite(pin, value);

pin is the number of the PWM-capable pin connected to the motor.

value is a number from 0 (off) to 255 (full speed) controlling motor speed.

Examples
This sets the motor speed to about half power on pin 9.
Arduino
analogWrite(9, 128);
This runs the motor at full speed on pin 5.
Arduino
analogWrite(5, 255);
This stops the motor by sending zero power on pin 3.
Arduino
analogWrite(3, 0);
Sample Program

This program slowly increases the motor speed in steps, then slowly decreases it, repeating forever.

Arduino
const int motorPin = 9;

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

void loop() {
  // Gradually increase speed
  for (int speed = 0; speed <= 255; speed += 51) {
    analogWrite(motorPin, speed);
    delay(1000); // wait 1 second
  }
  // Gradually decrease speed
  for (int speed = 255; speed >= 0; speed -= 51) {
    analogWrite(motorPin, speed);
    delay(1000); // wait 1 second
  }
}
OutputSuccess
Important Notes

Make sure your motor is connected to a PWM-capable pin on the Arduino (usually marked with ~).

Use a motor driver or transistor to protect your Arduino from high current.

Delay helps you see the speed changes clearly by waiting between steps.

Summary

PWM controls motor speed by changing power in quick pulses.

Use analogWrite() with values 0 to 255 to set speed.

Always connect motors safely with drivers or transistors.