Arduino Tutorials – Lesson 31 – Micro Metal Gear Motor with Encoder

Creating DC Motor position control program using Arduino UNO

Required Components

  1. Arduino MEGA2560 -1 no
  2. Motor control shield(L293D) -1 no
  3. Micro Metal Gear Motor with Encoder -2 no
  4. Motor Wheel -2 no
  5. Bread Board -1 no
  6. Jumper Wires(Male to Male) -11 no
  7. Voltage Converter(5V-3.3V) -1 no
  8. 5V Battery -1 no
  9. USB cable -1 no

Steps

  1. Make sure the components are working properly.
  2. Connect the 5V Battery to the L293D Motor Driver.
  3. Connect the micro motor M1,M2 pins to the L293D Motor Driver M3 & the second micro motor M1,M2 pins to the L293D Motor Driver M4 respectively .
  4. Connect the Arduino Mega board pins 5V, gnd to the voltage converter V IN, gnd properly.
  5. Connect the Voltage converter V Out, gnd pins to the micro motor gnd, vcc pins & the second micro motor gnd, vcc pins properly.
  6. Connect the micro motor C1,C2 pins to the Arduino Mega board pins 18,19 & the second micro motor C1,C2 pins to the Arduino Mega board pins 20,21 respectively.
  7. Check the Circuit Connections.
  8. Check the Arduino program.
  9. Run the Arduino program.

Arduino Program

#include <AFMotor.h>
#include <Encoder.h>
AF_DCMotor motor1(4);
AF_DCMotor motor2(3);
Encoder myEnc1(21,20);
Encoder myEnc2(18,19);
long oldPosition1  = -999;
long oldPosition2  = -999;
long m1Pos = 0;
long m1Dir = 0;
long m2Pos = 0;
long m2Dir = 0;
long md1=2000;
long md2=2000;

void setup()
{
  Serial.begin(9600);
  Serial.println("Motor test!");
  
  motor1.setSpeed(200);
  motor2.setSpeed(200);
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor1Move(md1,0);
  motor2Move(md2,0);
}

void loop()
{
  checkMotor1();
  checkMotor2();
  delay(5);
}

void motor1Move(int d1,int d2)
{
  m1Pos=d1;
  m1Dir = d2;
  if (d2==0)
  {
    motor1.run(FORWARD);
  }
  else if (d2==1)
  {
    motor1.run(BACKWARD);
  }
}

void motor2Move(int d1,int d2)
{
  m2Pos=d1;
  m2Dir = d2;
  if (d2==0)
  {
    motor2.run(FORWARD);
  }
  else if (d2==1)
  {
    motor2.run(BACKWARD);
  }
}

void checkMotor1()
{
  long newPosition1 = myEnc1.read();
  if (m1Dir==0)
  {
    if ( newPosition1>m1Pos)
    {
      m1Pos=0;
      motor1.run(RELEASE);
      myEnc1.write(0);
      motor1Move(md1,1);
    }
  }
  else
  {
    if ( abs(newPosition1)>m1Pos)
    {
      m1Pos=0;
      motor1.run(RELEASE);
      myEnc1.write(0);
      
      motor1Move(md1,0);
    }
  }
}

void checkMotor2()
{
  long newPosition2 = myEnc2.read();
  if (m2Dir==0)
  {
    if ( newPosition2>m2Pos)
    {
      m2Pos=0;
      motor2.run(RELEASE);
      myEnc2.write(0);
      motor2Move(md2,1);
    }
  }
  else
  {
    if ( abs(newPosition2)>m2Pos)
    {
      m2Pos=0;
      motor2.run(RELEASE);
      myEnc2.write(0);
      motor2Move(md2,0);
    }
  }
}