Making a motor which turns off after a set amount of time using millis

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");
}
}

I would replace the above line with startTme = millis(); because the 5000 ms for runTime may have lapsed before you press the button.

1 Like

nope, still doesn't fix anything, are there any other issues you could see with the code that I could correct. At this point I'm kinda all out of ideas

Okay. Can you post the output of what you have, and show where the error occurs?

so, I'm at home right now therefore i am using tinkercad for my arduino stuff, what the program should do is stop the motor and turn the green LED on once 5 seconds go by, but instead it just keeps counting past 5 and the motor keeps spinning:

This statement needs the two values to be exact, which they might not be...

 if (elapsedTime == runTime) {

try:

 if (elapsedTime >= runTime) {

so if elapsedTime exceeds 5000ms... (do something else)

1 Like

you're such a help honestly thank you so much, this solved it, been at this half the night and now I can sleep lol

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.