I didn't see a pin for speed control of motor B so I just picked pin #6.
/* MotorWithDelay
* By Duane Degn
* November 1, 2015
*/
const int IN1_MOTOR_A = 4;
const int IN2_MOTOR_A = 2;
const int IN1_MOTOR_B = 8;
const int IN2_MOTOR_B = 7;
const int ENABLE_MOTOR_A = 3;
const int ENABLE_MOTOR_B = 6; // I'm guessing
const int BETWEEN_MOTOR_DELAY = 2000; // I'm guessing
const int MIN_DELAY = 1000;
const int MAX_DELAY = 6000;
//unsigned long potReadTime;
//unsigned long endActionTime;
//duration;
void setup()
{
pinMode(IN1_MOTOR_A, OUTPUT);
pinMode(IN2_MOTOR_A, OUTPUT);
pinMode(IN1_MOTOR_B, OUTPUT);
pinMode(IN2_MOTOR_B, OUTPUT);
pinMode(A0,INPUT); //motor speed control
pinMode(A1,INPUT); //duration control
Serial.begin(9600);
}
void loop()
{
MonitorMotor(IN1_MOTOR_A, IN2_MOTOR_A, ENABLE_MOTOR_A);
delay(BETWEEN_MOTOR_DELAY);
MonitorMotor(IN1_MOTOR_B, IN2_MOTOR_B, ENABLE_MOTOR_B);
delay(BETWEEN_MOTOR_DELAY);
}
void MonitorMotor(int in1, int in2, int enable)
{
unsigned long duration;
unsigned long startTime = millis();
do
{
int rate = analogRead(A0);
rate = map(rate, 0, 1023, 0, 255); // Use this line for positive rates.
//rate = map(rate, 0, 1023, -255, 255); // Use this line to allow negative rates.
duration = analogRead(A1);
duration = map(duration, 0, 1023, MIN_DELAY, MAX_DELAY);
SetMotor(in1, in2, enable, rate);
Serial.print("rate = ");
Serial.print(rate);
Serial.print(", total duration = ");
Serial.print(duration);
Serial.print(", time remaing = ");
Serial.println(duration - (millis() - startTime));
}
while (millis() - startTime < duration);
}
void SetMotor(int in1, int in2, int enable, int power)
// "power" may be positive or negative.
// A negative power value will cause the motor to reverse.
{
if (power > 0)
{
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
}
else if (power == 0) // This will cause motor to brake.
{
digitalWrite(in1, LOW); // Comment out these two lines
digitalWrite(in2, LOW); // to coast to a stop.
}
else
{
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
power *= -1; // Set power to positive since motor has been set to reverse.
}
analogWrite(enable, power);
}
There's a two second delay between motors being powered on. You can change the amount of time with this constant.
const int BETWEEN_MOTOR_DELAY = 2000;
I used the same range for the maximum and minimum motor run times. Again, if you want to change these times, you can do so with these constants.
const int MIN_DELAY = 1000;
const int MAX_DELAY = 6000;
I wasn't sure if you wanted to be able to adjust the speed of the motors while they were running but I decided it would be interesting to be able to adjust both the speed and the duration on the fly so I included calculating the rate inside the loop which monitors the motor.
I'm relatively new to Arduinos but not programming and microcontrollers. I'm not sure if I have all the syntax correct or not. The program compiles but I haven't tested it.
I hope you let me know if it works as expected or not.