Go Down

Topic: How to make motors run for certain amount of time (Read 1 time) previous topic - next topic

natpen

Hello,

I'm just trying to run 5 DC motors through a PIR sensor through my Arduino Genuino Uno.
I can get them to go on when motion is sensed with the following code

Code: [Select]

// the setup funcion runs once when you press reset or power the board
void setup() { // <<start every new action with opening Brace
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(4, OUTPUT); // to the relay, to the motors
  pinMode(2, INPUT); // the PIR sensor
  // close every action with closing Brace

  // the loop function runs over and over again forecer
}  void loop() {
    if(digitalRead(2)==1){ // if the PIR sensor senses movement (1) (its 0 if not) then the sequence will begin

      digitalWrite(4, HIGH); // turn the RELAY on which turns the motors on (HIGH is the voltage level)
      digitalWrite(LED_BUILTIN, HIGH);
   
    }
    else{ // else means otherwise
      digitalWrite(4, LOW); //the power to the relay/motors will remain off
      digitalWrite(LED_BUILTIN, LOW);
    }
  } // must make sure every opening brace has a closing one



But I want the motors to stay on for 2 minutes, what would i need to add into my code to do this?

Thank you!

slipstick

If you just want the motors always to run (and the LED to be on) for two minutes once the PIR has triggered you can just add a delay.

Code: [Select]
    if(digitalRead(2)==1){ // if the PIR sensor senses movement (1) (its 0 if not) then the sequence will begin

      digitalWrite(4, HIGH); // turn the RELAY on which turns the motors on (HIGH is the voltage level)
      digitalWrite(LED_BUILTIN, HIGH);
      delay(120000)



Delay is in microseconds so 120000 is approximately 2 minutes. It's not 100% accurate so if you need EXACTLY 2 minutes you'll need to do it another way. BTW for initial testing you might want to use a smaller number, 2 minutes is a LONG time to wait for something to happen.

That should run the motors for 2 minutes and then loop round to check the PIR again. If the PIR still senses movement then the motors will run for another 2 minutes before checking again.

There are plenty of other ways of achieving something similar but this is probably the easiest.

Steve

Go Up