Example Code for Arduino-Motor Control
The article offers a detailed guide on controlling a motor using Arduino, covering hardware and software setup, wiring diagrams, and sample code for precise control using pulse width signals, ensuring effective management of motor speed and direction.
Hardware Preparation
- DFRduino UNO x1, Purchase Link: arduino UNO
- DFR0399 Gear Motor x1, Purchase Link: DFR0399
Software Preparation
- Arduino IDE Click to Download Arduino IDE from Arduino®
Wiring Diagram

Other Preparation Work
"0~180" degree corresponds to the pulse width signal "500us~2500us".
When we give a value between 81~99° (1400~1600us), the motor will stop;
When we give a value less than 81° (1400us), the motor rotates clockwise, the smaller the value, the faster the speed, 0° (500us) is the maximum speed;
When we give a value greater than 99° (1600us), the motor rotates anticlockwise, the larger the value, the faster the speed, 180 ° (2500us) is the maximum speed;
Since every motor has a little difference, we enlarge the stop range to ensure that the motor can be stopped correctly.
Sample Code
#include <Servo.h>
#define speed_maxP 0 //Clockwise rotation (Max speed)
#define speed_maxN 180 //Anticlockwise rotation (Max speed)
#define speed_stop 90 //Stop
Servo mymotor; // create servo object to control a servo (my motor)
// twelve servo objects can be created on most boards
int pos=0;
void setup()
{
mymotor.attach(9); //attaches the motor on pin 9 to the servo object
}
void loop()
{
/**********Using 180 degree servo library to control N20 motor******************************/
mymotor.write(speed_stop); //Stop
delay(1000); //delay 1s
mymotor.write(speed_maxP); //Clockwise rotation
delay(2000); //delay 2s
mymotor.write(speed_maxN); //Anticlockwise rotation
delay(2000); //delay 2s
for(pos=speed_maxP;pos<speed_maxN;pos++) //slow down, change the direction and speed up
{
mymotor.write(pos);
delay(50);
}
}
Result
When this Arduino code runs, the N20 motor will perform a repeating cycle of movements as follows:
First, it stops rotating for 1 second.
Then, it spins clockwise at maximum speed for 2 seconds.
Next, it switches to spinning anticlockwise at maximum speed for another 2 seconds.
Finally, it smoothly transitions from maximum clockwise speed to maximum anticlockwise speed: the motor gradually slows down until it stops, then immediately gradually speeds up in the opposite (anticlockwise) direction. This smooth transition takes about 9 seconds.
The entire above cycle repeats indefinitely until the Arduino is powered off or new code is uploaded.
Was this article helpful?
