Creating DC Motor position control program using Arduino UNO
Required Components
- Arduino MEGA2560 -1 no
- Motor control shield(L293D) -1 no
- Micro Metal Gear Motor with Encoder -2 no
- Motor Wheel -2 no
- Bread Board -1 no
- Jumper Wires(Male to Male) -11 no
- Voltage Converter(5V-3.3V) -1 no
- 5V Battery -1 no
- USB cable -1 no
Steps
- Make sure the components are working properly.
- Connect the 5V Battery to the L293D Motor Driver.
- 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 .
- Connect the Arduino Mega board pins 5V, gnd to the voltage converter V IN, gnd properly.
- Connect the Voltage converter V Out, gnd pins to the micro motor gnd, vcc pins & the second micro motor gnd, vcc pins properly.
- 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.
- Check the Circuit Connections.
- Check the Arduino program.
- 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);
}
}
}