Hi Guys,
I am using a UNO R3 with relay to start and stop a motor. When a momentary contact push button is pressed, I would like the motor to run for 5 seconds and then stop.
The code below only works if I add a 1 ms delay in the checkStartSwitch() function (3rd line from the bottom). If I remove the 1ms delay, the motor starts when the push button is pressed, but it does not stop. It tries to stop every 5 seconds (ie. I can hear the relay click like it is trying to stop) but the motor just keeps on going.
It doesn't make sense to me. Any ideas why I can't remove the delay?
Don
const int startSwitch = A0;
const int mainInclineMotor = 4;
enum startButtonStates{IS_PRESSED = 0, IS_RELEASED = 1};
enum motorControlStates{ON = 0, OFF = 1};
// set the time limit to 5 seconds and the current time to 0.
const long timeLimit = 5000;
unsigned long currentTime = 0;
void setup() {
pinMode(startSwitch, INPUT_PULLUP);
pinMode(mainInclineMotor, OUTPUT);
//turn off all motors off during setup (note that the output pins are "active" low)
digitalWrite(mainInclineMotor, OFF);
//initialize serial communication with terminal
Serial.begin(9600);
}
//main program loop runs continuously over and over again.
void loop(){
checkStartSwitch ();
}
void checkStartSwitch(){
// this function turns on the mainInclineMotor when the startSwitch is pressed
// and turns off the mainInclineMotor when the timer is complete.
if (digitalRead(startSwitch) == IS_PRESSED) {
// If it is the first time through this function, set the currentTime to millis and turn on the mainInclineMotor.
// On subsequent passes, this skip these two steps.
if (currentTime == 0) {
currentTime = millis();
digitalWrite(mainInclineMotor, ON);
}
}
// If the timer is finished, then turn off the mainInclineMotor and reset the currentTime back to "0"
if (millis() - currentTime >= timeLimit) {
digitalWrite(mainInclineMotor, OFF);
currentTime = 0;
delay (1);
}
}