Hi,
I have an h-bridge with a single motor and I’ve got the motor rotating ‘forward’ at speed 100 for 4 seconds, I then double the speed and let it run for another 4 seconds. I then set the motor to rotate in reverse at speed 100 for 2 seconds followed by rotating in reverse at double the speed for another 2 seconds. The code then transitions back to the top of the loop and runs the same sequence over again.
When I run this code the first reverse step doesn’t execute ie the motor doesn’t run in reverse, however it does wait the required amount of time. The subsequent reverse step at twice the speed does work as expected as do the forward steps.
The code isn’t complicated, I just can’t think of why the first reverse wouldn’t execute, particularly when the second reverse call does.
// Constants
const int enableBridge1 = 2;
const int MotorForward1 = 3;
const int MotorReverse1 = 4;
const int MotorForward2 = 5;
const int MotorReverse2 = 6;
const int STOP = 0;
const int FORWARD = 1;
const int REVERSE = 2;
const int LEFT = 1;
const int RIGHT = 2 ;
void setup(){
Serial.begin (115200);
pinMode(MotorForward1,OUTPUT);
pinMode(MotorReverse1,OUTPUT);
pinMode(enableBridge1,OUTPUT);
digitalWrite(enableBridge1,HIGH); // Enable Hbridge 1
}
void loop(){
Serial.println ("Forward 100");
runMotor(LEFT, FORWARD, 100,4000);
Serial.println ("Forward 200");
runMotor(LEFT, FORWARD, 200,4000);
Serial.println ("Reverse 100");
runMotor(LEFT, REVERSE, 100,2000);
Serial.println ("Reverse 200");
runMotor(LEFT, REVERSE, 200,2000);
}
void runMotor(int motor, int mode, int power, int delayAmount){
if (motor == LEFT){
if (mode == FORWARD){
analogWrite(MotorReverse1,0);
analogWrite(MotorForward1,power);
}
if (mode == REVERSE){
Serial.println ("yup in here!");
analogWrite(MotorForward1,0);
analogWrite(MotorReverse1,power);
}
if (mode == STOP){
analogWrite(MotorForward1,0);
analogWrite(MotorReverse1,0);
}
} else if (motor == RIGHT){
if (mode == FORWARD){
analogWrite(MotorReverse2,0);
analogWrite(MotorForward2,power);
}
if (mode == REVERSE){
analogWrite(MotorForward2,0);
analogWrite(MotorReverse2,power);
}
if (mode == STOP){
analogWrite(MotorForward2,0);
analogWrite(MotorReverse2,0);
}
} else{
// all stop
analogWrite(MotorReverse1,0);
analogWrite(MotorForward1,0);
analogWrite(MotorReverse2,0);
analogWrite(MotorForward2,0);
}
if (delayAmount >0){
delay(delayAmount);
}
}