How to Control Motor Speed Using Arduino: Simple Guide
You can control motor speed using Arduino by sending
PWM signals to the motor driver or motor pin. Use the analogWrite(pin, value) function where value ranges from 0 (stop) to 255 (full speed) to adjust speed smoothly.Syntax
The main function to control motor speed with Arduino is analogWrite(pin, value).
pin: The Arduino pin connected to the motor driver or motor control input.value: A number from 0 to 255 representing the speed (0 = stop, 255 = full speed).
This function sends a PWM (Pulse Width Modulation) signal to control the motor speed.
arduino
analogWrite(pin, value);
Example
This example shows how to control a DC motor speed connected to pin 9 using PWM. The motor speed increases from 0 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); // Set motor speed delay(20); // Wait 20ms for smooth 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 back to stop repeatedly.
Common Pitfalls
- Using digitalWrite instead of analogWrite:
digitalWriteonly turns the motor fully ON or OFF, no speed control. - Wrong pin selection: Only PWM-capable pins (marked with ~ on Arduino Uno) support
analogWrite. - Not using a motor driver: Arduino pins cannot supply enough current; always use a motor driver or transistor.
- Ignoring motor power supply: Motor should have its own power source, not just Arduino 5V pin.
arduino
/* Wrong way: No speed control */ digitalWrite(9, HIGH); // Motor runs full speed only /* Right way: Speed control with PWM */ analogWrite(9, 128); // Motor runs at half speed
Quick Reference
Remember these tips when controlling motor speed with Arduino:
- Use
analogWriteon PWM pins only. - Value range: 0 (stop) to 255 (full speed).
- Use a motor driver or transistor to handle current.
- Provide separate power supply for the motor.
Key Takeaways
Use analogWrite(pin, value) with PWM pins to control motor speed smoothly.
Value 0 stops the motor; 255 runs it at full speed.
Always use a motor driver or transistor to protect Arduino pins.
Provide a separate power source for the motor to avoid damage.
Avoid digitalWrite for speed control as it only turns motor fully on or off.