Want to rotate DC motor forward for 5 sec only,Then reverse for 5 sec again.

// Help Required!!!
Hello there, I am making a door lock system using pir sensor. What I want is that whenever motion is detected by sensor i.e logic state is HIGH, DC motor moves in one direction only for 5 sec(i.e gate opens). Then when again motion is detected or logic state is LOW, DC motor moves reverse for 5 sec. My code is all working except that motor moves continuously and don’t stops in any case. Here is my code:
//Hardware is PIR Sensor , Simple DC motor, L293D motor driver, Arduino uno.

int motor1=7;
int motor2=6;
int pir=10;
int pos=0;
int gate_open=false;
void setup()
{
//pinMode(motor,OUTPUT);
pinMode(pir,INPUT);
pinMode(motor1,OUTPUT);
pinMode(motor2,OUTPUT);
}

void loop() {
if(digitalRead(pir)==HIGH)
{
digitalWrite(motor1,HIGH);
digitalWrite(motor2,LOW);
delay(500);
gate_open=true;
}
if(digitalRead(pir)==LOW && gate_open==true)
{
digitalWrite(motor1,LOW);
digitalWrite(motor2,HIGH);
delay(500);
gate_open=false;
}

Are you aware that delay(500) is 500 millisecs or half a second. Maybe you just need to change that to 5000 for 5 seconds?

For a more comprehensive approach have a look at how millis() is used to manage timing without blocking in Several things at a time. And see Using millis() for timing. A beginners guide if you need more explanation.

...R

sheikhtoocool:
My code is all working except that motor moves continuously and don't stops in any case.

That's because you never stop the motor. Once it starts running it is always running in one direction or the other.

Perhaps after each delay() you should set motor1 and motor2 to some values that will cause the motor to stop (probably LOW and LOW but that depends on exactly how you have the motor driver wired).

Steve