Example Code for Arduino-Motor Control

Last revision 2026/01/17

This article provides detailed guidance on controlling N20 motors using Arduino and the Servo library, including hardware and software preparations, a wiring diagram, and example code for motor rotation. It discusses setting motor speeds, stopping, and direction changes with specific pulse width signals, ensuring precise control and effective execution of motor functions.

Hardware Preparation

  • DFRduino UNO x1
  • DFR1114 Integrated Drive N20 Motor x1

Software Preparation

Wiring Diagram

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);
  }
}

Additional Information

  • "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;

Was this article helpful?

TOP