how to control motor with ultrasonic sensor

how to reset the “millis code” because the code only run once…i want the motor will run 3 second and stop without the ultrasonic coding…how to do that?
can someone help me with the coding…

int trigPin = 6;
int echoPin = 7;
int aa = 9; // motor 1
int ab = 10;
int ba = 11; // motor 2
int bb = 12;

long duration, distance;
long int stop1;

void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(aa, OUTPUT); // set pins to output
pinMode(ab, OUTPUT);
pinMode(bb, OUTPUT);
pinMode(ba, OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
stop1=millis()+3000;
}

void loop()
{
// put your main code here, to run repeatedly:
digitalWrite(trigPin,HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration=pulseIn(echoPin, HIGH);
distance =(duration/2)/29.1;
Serial.print(distance);
Serial.println(“CM”);
delay(10);

fillingwaterintank();
delay(100);

if (millis()<stop1)
{
digitalWrite(11,HIGH); // motor 1
}
else
{
digitalWrite(11,LOW); // motor 1
}
}

void fillingwaterintank()
{
if((distance>40)) // DETECT the distance and run the motor
{
digitalWrite(9,HIGH); // motor 1
digitalWrite(10,LOW);
delay(100);
}

else if(distance<20) // DETECT the distance and stop the motor
{
digitalWrite(9,LOW); // motor 1
digitalWrite(10,LOW);
delay(100);
}
}

You need to learn how to use the millis() timer. See this tutorial.

thank for the info :slight_smile:

Code like this:

  if (millis()<stop1)

will go wrong when the millis() value wraps round (its 32 bit, so this takes a while, about 50 days,
but the same issue with the micros() value takes only 70 minutes.

If you want something to happen once, use a flag (boolean variable) to record if its already happened
to stop it happening more times.