I got my first Arduino kit (Arduino Mega 2560) and i am trying to control the position a 24V DC motor using a single bit encoder. The encoder has got a low resolution of 30 pulses/rev. I am using a dual DC motor driver to drive the motor. I have done the coding as shown below. But the motor is not working. I have provided common ground to the DC motor driver, encoder and Arduino by connecting the ground pins of motor driver and encoder to the Arduino. The encoder which needs 5V is provided from the Arduino 5V pin. Please see the code. It is supposed to stop the motor after one rotation is completd.
int motor1PinA = 14;
int motor1PinB = 15;
int motorpwm = 3;
int encoder1Pin = 2;
volatile int encoder1Pos = 0;
int theta1 = 360;
void setup() {
pinMode(motor1PinA, OUTPUT);
pinMode(motor1PinB, OUTPUT);
pinMode(motorpwm, OUTPUT);
pinMode(encoder1Pin, INPUT);
attachInterrupt(0, encoder1svc, HIGH);
digitalWrite(motor1PinA, LOW);
digitalWrite(motor1PinB, LOW);
digitalWrite(motorpwm, LOW);
}
void loop() {
digitalWrite(motor1PinA, HIGH);
if (encoder1Pos*12 >= theta1)
digitalWrite(motor1PinB, HIGH);
encoder1Pos = 0;
}
void encoder1svc()
{
if (digitalRead(encoder1Pin) == HIGH)
encoder1Pos++;
}