controlling the time for which dc motor rotates through the code.

hey!
I want to control the time for which dc motor runs preferably using the code.
I have used l298n for driver and there's a push button circuit too. pressing the push button once should rotate the motor in say clockwise direction and the next time anticlockwise.
this is the code i have. the timer part is not working. without the timer part the switching between clockwise and anticlockwise works but with the timer part it just continuously rotates in one direction.
PLEASE HELP ME WITH THE CODE.

CODE*

//Motor A
int dir1PinA = 13;
int dir2PinA = 12;

unsigned long interval=1000;
unsigned long time1=0;
unsigned long time2;
int count=0;
void setup ()
{
pinMode (dir1PinA, OUTPUT);
pinMode (dir2PinA, OUTPUT);

Serial.begin(9600);

}

void loop ()
{
int sensorValue = analogRead(A0);

//set direction
if (sensorValue >= 400 && count%2 ==0)
{

time2=millis();
while (time2-time1<=interval)
{
time1=time2;
digitalWrite (dir1PinA , LOW);
digitalWrite (dir2PinA, HIGH);
time2=millis();
}
}
else if (sensorValue >= 400 && count%2!=0)
{
time2=millis();
while (time2-time1<=interval)
{
time1=time2;
digitalWrite (dir1PinA , HIGH);
digitalWrite (dir2PinA, LOW);
time2=millis();
}

}
count++;
}

    time2=millis();
    while (time2-time1<=interval) {
      time1=time2;
      digitalWrite (dir1PinA , LOW); 
      digitalWrite (dir2PinA, HIGH); 
      time2=millis();
    }

That means:
get the current time
while it has been less than a second since the timer was started:
re-start the timer (This is your mistake. Don't re-start the timer while waiting for it to time out)
do something
get the new current time

okay yeah i realized! thank you :slight_smile:

Congratulations on re-inventing delay(). Now, why did you do that?