for my college exams i'm making a program which runs a motor along side two LEDs one which will turn on after a button is pressed and turns off with the motor, and the other which turns on after the motor has stopped. I'm having trouble with the time keeping part though, the motor doesn't stop after the set time has passed. Still relatively new to arduino, just wondering what I could be doing wrong here:
int button = 2;
int relay = 7;
int buttonState = 0;
int LEDGREEN = 3;
int LEDRED = 4;
int flag = 1;
int runTime = 5000;
unsigned long currentTime = 0;
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
void setup() {
pinMode(button, INPUT_PULLUP);
pinMode(relay, OUTPUT);
pinMode(LEDGREEN, OUTPUT);
pinMode(LEDRED, OUTPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(button);
currentTime = millis();
if(buttonState == LOW && flag == 1){
digitalWrite(relay, HIGH);
digitalWrite(LEDRED, HIGH);
startTime = currentTime;
flag = 0;
}
if(buttonState == LOW){
elapsedTime = (currentTime - startTime);
Serial.println("time since button was pressed ");
Serial.print(elapsedTime/1000);
Serial.println(" seconds");
}
if(elapsedTime == runTime){
digitalWrite(relay, LOW);
digitalWrite(LEDGREEN, HIGH);
}
if(buttonState == HIGH){
flag = 1;
startTime = 0;
elapsedTime = 0;
Serial.println("button not pressed");
}
}