Automatic Hand Sanitizer Timing

I am planning to make an automatic hand sanitizer as my school project. If i do not remove hand from ultrasonic sensor, pump is running continuously. I have no idea what kind of function i can use to restrict pump running continuously if someone do not remove hand from the sensor. Could you please guide me on the program? Thanks in advance. Here is the code.

const int trigPin = 12;
const int echoPin = 13;
#define DCwater_pump 8
// defines pins
long duration;
int distance;

void setup()
{
pinMode (2,OUTPUT);
pinMode (trigPin,OUTPUT);
pinMode (echoPin,INPUT);
pinMode(DCwater_pump, OUTPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(trigPin,LOW);
delayMicroseconds (2);
digitalWrite(trigPin,HIGH);
delayMicroseconds (10);
digitalWrite(trigPin,LOW);
duration = pulseIn(echoPin,HIGH);
digitalWrite(trigPin,HIGH);
distance = duration*0.034/2;
Serial.print("Distance: ");
Serial.println(distance);
if (distance <=10) //can be adjusted from 2cm to 400cm
{
digitalWrite(2,LOW);
digitalWrite(DCwater_pump,HIGH);
Serial.println("DC Pump is ON Now!!");
}
else
{
digitalWrite(2,HIGH);
digitalWrite(DCwater_pump,LOW);
Serial.println("DC Pump is OFF Now!!");
delay(100); // can be adjusted
}
}

Use an enableFlag variable.

When your sensor detects an object, and an enableFlag is set , turn on a pump for a given amount of time then reset the enableFlag.

When the sensor does not detect an object, set the enableFlag.

did you mean set the enableFlag = false ?

by the way You should post code by using code-tags
There is an automatic function for doing this in the Arduino-IDE
just three steps

  1. press Ctrl-T for autoformatting your code
  2. do a rightclick with the mouse and choose "copy for forum"
  3. paste clipboard into write-window of a posting

best regards Stefan

set can be true
reset can be false
or vice versa

could use #define . . .

#define SET true
#define RESET false
or
#define ENABLED true
#define DISABLED false


#define SET     true
#define RESET   false
. . .
bool enableFlag = SET;
. . .
if (distance <=10 &&  enableFlag == SET) //can be adjusted from 2cm to 400cm
{
  digitalWrite(2,LOW);
  digitalWrite(DCwater_pump,HIGH);
  Serial.println("DC Pump is ON Now!!");
  delay(500); // pump on for 1/2 second

  enableFlag = RESET; //we only want the pump on one time

  digitalWrite(2,HIGH);
  digitalWrite(DCwater_pump,LOW);
  Serial.println("DC Pump is OFF Now!!");
}

if( distance > 20  ) // adjust as needed
{
  enableFlag = SET; //allow pump to turn ON
}

Alright thanks

Thank you so much it works