Example Code for Arduino-Motor Speed and Direction Control
Last revision 2025/12/29
Here is a example how to use this motor, Just follow the guide, and you will get it work.
Hardware Preparation
- UNO x1
- Motor x1
Software Preparation
- Arduino IDE V1.6.5 Click to Download Arduino IDE
Wiring Diagram
![]() |
NOTE: Remember to connect Arduino GND to the POWER-. |
|---|
Other Preparation Work
- Open the Arduino IDE and copy the following code to the IDE. Select your board's serial port and the board type (e.g. Arduino UNO) and upload the sample code.
- Open the Serial monitor.
- Enter a number between 0 and 255 to set the motor's speed. (0: Maxmum speed; 255: Stop)
- The code will alternates its rotation direction every 5 seconds.
Sample Code
int i = 0;
unsigned long time = 0;
bool flag = HIGH;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(10, OUTPUT); //direction control PIN 10 with direction wire
pinMode(11, OUTPUT); //PWM PIN 11 with PWM wire
}
void loop() {
// put your main code here, to run repeatedly:
if (millis() - time > 5000) {
flag = !flag;
digitalWrite(10, flag);
time = millis();
}
if (Serial.available()) {
analogWrite(11, Serial.parseInt()); //input speed (must be int)
delay(200);
}
for(int j = 0;j<8;j++) {
i += pulseIn(9, HIGH, 500000); //SIGNAL OUTPUT PIN 9 with white line,cycle = 2*i,1s = 1000000us,Signal cycle pulse number:27*2
}
i = i >> 3;
Serial.print(111111 / i); //speed r/min (60*1000000/(45*6*2*i))
Serial.println(" r/min");
i = 0;
}
Result
Was this article helpful?

