Hello! I have this code to control the direction of spin on a DC motor. When one button is pressed the motor continuously spins clockwise. When the second button is pressed, the motor spin immediately changes direction. Is there a way to add a 5 second delay after either button is pressed? So the button is pressed, the motor stops for 5 seconds, then turns on in the opposite direction. When the second button is pressed, the process is repeated.
Thank you!
int in1pin = 6;
int in2pin = 7; // h bridge pins
int leftButton = 8;
int rightButton = 9; // buttons
void setup() {
pinMode(in1pin, OUTPUT);
pinMode(in2pin, OUTPUT); // outputs
pinMode(leftButton, INPUT_PULLUP);
pinMode(rightButton, INPUT_PULLUP); // inputs w internal pullup resistors
}
void loop() {
int leftPinState = digitalRead(leftButton);
int rightPinState = digitalRead(rightButton); // set value names for read data
if (leftPinState == LOW) { // if left button is pressed ...
digitalWrite(in1pin, HIGH); // make motor go one way
digitalWrite(in2pin, LOW);
}
else if (rightPinState == LOW) { // if right button is pressed ...
digitalWrite(in1pin, LOW);
digitalWrite(in2pin, HIGH); // make motor go other way
}
else { // if neither button is pressed ...
digitalWrite(in1pin, LOW); // nothing happens
digitalWrite(in2pin, LOW);
}
}
Whenever a button is pressed, there should be a pause. So if the other button is pressed 2 seconds after the other one, the time delay resets to pause for 5 seconds from the time that the other button was pressed.
Can you draw a flow chart as to how your program will work. It makes it much easier to write and debug. Is this a school project? Have you done anything like this before?
This is a personal project, and no, I have not attempted something like this. The operations should go like this, assuming the motor starts at rest:
Button 1 is pressed>>>>>>Wait 5 seconds>>>>>Activate motor in the clockwise direction>>>>>> Button 2 is pressed (after at least 20 seconds of the motor running)>>>>>Shut motor off for 5 seconds>>>>>>Reactivate motor but in the counterclockwise direction>>>>>>>Button 1 is pressed (after at least 20 seconds of the motor running)>>>>>Shut motor off for 5 seconds>>>>>>Reactivate motor but in the clockwise direction>>>>>>>Repeat until Arduino is turned off.
Right now, the motor immediately changes direction with each button press. There is no delay.
Do you have the Arduino Cookbook. Do you know how to do non blocking delays same as the blink without delay?
Consider when a button is pressed it sets a variable true of false, the second button sets it the opposite. This tells you which direction/last button. When you set the variable you start the 5 second delay and if it times out you start the motor. for 20 seconds.