Hi all,
I am trying to use the arduino board with the motor shield to control the speed of the motor. I have tried to control the motor speed using the following command:
void motor1(int high_low1, int pwm1)
{
digitalWrite(EN1,high_low1);
analogWrite(IN1,pwm1);
}void motor2(int high_low2, int pwm2)
{
digitalWrite(EN2,high_low2);
analogWrite(IN2,pwm2);
}void loop()
{
motor1(high, 180);
motor2(high, 180);
}
However, when i test the motor with the vehicle, the vehicle cannot move straightly. Then i tried to use a motor embedded with an encoder to do the dc motor feedback control. The speed of the left motor is kept constant while the speed of the right motor is changed. If the pulse count on the left motor is larger, the speed of the right motor increases. If the pulse count on the right motor is larger, the speed of the right motor decreases. However, this program also doesn’t work as after some time speed of the right motor will keep increasing or keep decreasing.
int IN1 = 6;
int EN1 = 7;
int IN2 = 5;
int EN2 = 4;
int encoder0count = 0; //encoder for left motor
int encoder1count = 0; //encoder for right motor
int encoder0PinA = 2;
int encoder1PinA = 8;
int encoder0PinALast = LOW;
int encoder1PinALast = LOW;
int n0 = LOW;
int n1 = LOW;
int l_pwm = 180; //speed of left motor
int r_pwm = 180; // speed of right motor
int timer = 0;void setup()
{
Serial.begin(115200);
}void loop()
{motor1(HIGH,l_pwm);
motor2(HIGH,r_pwm);n0 = digitalRead(encoder0PinA);
if ((encoder0PinALast == LOW) && (n0 == HIGH)) {encoder0count++;
}
encoder0PinALast = n0;n1 = digitalRead(encoder1PinA);
if ((encoder1PinALast == LOW) && (n1 == HIGH)) {encoder1count++;
}
encoder1PinALast = n1;Serial.print(encoder0count);
Serial.print(" “);
Serial.print(encoder1count);
Serial.print(” “);
Serial.print(l_pwm);
Serial.print(” “);
Serial.print(r_pwm);
Serial.println(” ");if (timer ==100)
{if (encoder0count < encoder1count)
{
r_pwm–;
}else if (encoder0count > encoder1count)
{
r_pwm++;
}encoder0count = 0;
encoder1count = 0;
timer = 0;}
timer++;
}void motor1(int high_low1, int pwm1)
{
digitalWrite(EN1,high_low1);
analogWrite(IN1,pwm1);
}void motor2(int high_low2, int pwm2)
{
digitalWrite(EN2,high_low2);
analogWrite(IN2,pwm2);
}
I want to ask whether there are something wrong in the program or there are any other ways to control the motor speed so the vehicle can move straight.