Example Code for Arduino-Motor Speed Control
This article offers a detailed guide on controlling the speed of DC motors using Arduino, including hardware and software requirements, a wiring diagram, and sample code. It explains how to setup the Arduino IDE and provides a loop function that varies motor speed from zero to maximum, suitable for DIY projects.
Hardware Preparation
- 1 x DFRduino UNO R3
- 1 x Dual Motor Driver (TB6612)
- 8 x Breadboard Jumper Cables
- 2 x DC Motor
- 5 x AA Battery
Software Preparation
- Arduino IDE Download Arduino IDE
Wiring Diagram

Sample Code
int PWM1 = 5;
int DIR1 = 4;
int PWM2 = 6;
int DIR2 = 7;
void setup()
{
pinMode(DIR1, OUTPUT);
pinMode(DIR2, OUTPUT);
}
void loop()
{
int value;
for(value = 0 ; value <= 255; value =5)
{
digitalWrite(DIR1,HIGH);
digitalWrite(DIR2, HIGH);
analogWrite(PWM1, value); //PWM Speed Control
analogWrite(PWM2, value); //PWM Speed Control
delay(30);
}
}
Result
Two motor speeds change from 0 to maximum, cycle.
Was this article helpful?
