0
0
AutocadHow-ToBeginner · 3 min read

How to Control Motor Speed with Arduino: Simple Guide

To control motor speed with Arduino, use analogWrite() on a PWM-enabled pin connected to the motor driver or transistor. Adjust the speed by changing the PWM value between 0 (stop) and 255 (full speed).
📐

Syntax

The main function to control motor speed is analogWrite(pin, value).

  • pin: The Arduino pin connected to the motor control (must support PWM).
  • value: Speed value from 0 (off) to 255 (full speed).

This sends a PWM signal to the motor driver, controlling the motor speed smoothly.

arduino
analogWrite(pin, value);
💻

Example

This example shows how to control a DC motor speed using a PWM pin. The motor speed increases from stop to full speed gradually.

arduino
const int motorPin = 9; // PWM pin connected to motor driver

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

void loop() {
  // Increase speed from 0 to 255
  for (int speed = 0; speed <= 255; speed++) {
    analogWrite(motorPin, speed);
    delay(20); // wait 20ms for smooth speed change
  }
  // Decrease speed from 255 to 0
  for (int speed = 255; speed >= 0; speed--) {
    analogWrite(motorPin, speed);
    delay(20);
  }
}
Output
Motor speed smoothly increases from stop to full speed and then decreases back to stop repeatedly.
⚠️

Common Pitfalls

  • Using a non-PWM pin with analogWrite() will not control speed properly.
  • Connecting the motor directly to Arduino pin without a driver or transistor can damage the board.
  • Not providing a proper power source for the motor can cause erratic behavior.
  • For motors needing direction control, speed control alone is not enough; use an H-bridge driver.
arduino
/* Wrong: Using a digital pin without PWM support */
const int motorPin = 2; // Pin 2 is not PWM on most Arduino boards

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

void loop() {
  analogWrite(motorPin, 128); // This will not work as expected
  delay(1000);
}

/* Right: Use PWM pin like 3, 5, 6, 9, 10, 11 on Arduino Uno */
const int motorPinPWM = 9;

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

void loop() {
  analogWrite(motorPinPWM, 128); // Half speed
  delay(1000);
}
📊

Quick Reference

Tips for controlling motor speed with Arduino:

  • Use PWM pins (3, 5, 6, 9, 10, 11 on Arduino Uno).
  • Use analogWrite(pin, value) where value is 0-255.
  • Always use a motor driver or transistor to protect Arduino.
  • Provide separate power supply for motors if needed.
  • Use delays or timers for smooth speed changes.

Key Takeaways

Use PWM pins and analogWrite() to control motor speed smoothly.
Never connect motors directly to Arduino pins; always use a driver or transistor.
Adjust PWM value from 0 to 255 to set motor speed from stop to full speed.
Provide proper power supply to avoid motor and board damage.
Use gradual speed changes with delays for smooth motor operation.