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

Creating DC Motor control with precise position 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 -1 no
  4. Motor Wheel -1 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 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 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);
Encoder myEnc1(18,19);
long oldPosition1  = -999;
long m1Pos = 0;
long m1Dir = 0;
long md1=2000;


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

void loop()
{
  checkMotor1();
  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 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);
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *