I am trying to control 2 small dc motors using two joystick potentiometers but im having trouble with the code.
My code:
//Arduino control of two motors via an H bridge using two joysticks
#define enA 6 //Enable A on H bridge connected to 6
#define in1 4
#define in2 7
#define enB 5 //Enable B on H bridge connected to 5
#define in3 3
#define in4 2
int motorSpeedA = 0;
int motorSpeedB = 0;
void setup()
{
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
Serial.begin( 9600 );
}
void loop()
{
int Ain = analogRead(A0); // Read Pot A
int Bin = analogRead(A1); // Read Pot B
if (Ain < 505)
{
// Set Motor A backward
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
motorSpeedA = map(Ain, 505, 0, 0, 255);
}
else if (Ain > 515)
{
// Set Motor A forward
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
motorSpeedA = map(Ain, 515, 1023, 0, 255);
}
if (Bin < 505)
{
// Set Motor B backward
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
motorSpeedB = map(Bin, 505, 0, 0, 255);
}
else if (Bin > 515)
{
// Set Motor B forward
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
motorSpeedB = map(Bin, 515, 1023, 0, 255);
}
else
{
motorSpeedA = 0;
motorSpeedB = 0;
}
analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
analogWrite(enB, motorSpeedB); // Send PWM signal to motor B
Serial.print(Ain );
Serial.print (" Motor A Speed ");
Serial.print(motorSpeedA);
Serial.print (" : ");
Serial.print(Bin );
Serial.print (" Motor B Speed ");
Serial.print(motorSpeedB);
Serial.println ();
}
The last Serial print lines are just there to see what's happening on the serial monitor.
the program almost works.
But motor A will only work if motor B is turning.
Motor B will work perfectly in both directions irrespective of motor A.
Its not wiring because Serial print shows no output on (motorSpeedA)
If I swap the sections of the script, so B is before A the symptoms are reversed.
A works perfectly but B only works when A is turning.
Any help or guidance appreciated