AUTOMATIC SANITISER

Guys,

I was making a automatic sanitizer dispenser using ultrasonic and dc pump.
now am facing a problem

I have set the distance ton turn on the pump to less than 10cm
but it detects the surfaces even at at a far distance, this keeps my pump is running even with out detecting the hands.

Please help me out its urgent;

My code is attached here;

/*------------------AUTOMATIC SANITIZER DISPENSER--------------------------------------------*/
/*_____________________USING ULTRASONIC SENSOR_______________________________________________*/
int const pump = 8;
int const uvcc = 9; //vcc to ultrasonic
int const trig = 10;
int const echo = 11;
int const ugnd = 12; //GND to ultrasonic
int const power = A4; // power indicator
int const disp = A5;  //Dispensing indicator
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
  // put your setup code here, to run once:
pinMode(pump,OUTPUT);
pinMode(uvcc,OUTPUT);
pinMode(trig,OUTPUT);
pinMode(echo,INPUT);
pinMode(ugnd,OUTPUT);
pinMode(power,OUTPUT);
pinMode(disp,OUTPUT);
digitalWrite(pump,LOW);
digitalWrite(uvcc,HIGH);  //VCC to ultrasonic
digitalWrite(ugnd,LOW);   //GND to ultrasonic
digitalWrite(power,LOW);
digitalWrite(disp,HIGH);  //Dispensing indicator

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(pump, LOW);
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = duration * 0.034 / 2;
  if(distance <10 && distance >1)
  {
    sanitise();
  }
  else
  {
    search_for_hand();
  }
}
void sanitise()
{
  digitalWrite(pump, HIGH);
  digitalWrite(disp, LOW);
  digitalWrite(uvcc, LOW);  //VCC to ultrasonic, SENSOR IS OFF
  delay(300);
  digitalWrite(pump, LOW);
  digitalWrite(disp, HIGH);
  delay(3000);
  digitalWrite(uvcc, HIGH);  //VCC to ultrasonic, SENSOR IS ON
}
void search_for_hand()
{
  digitalWrite(uvcc, HIGH); //VCC to ultrasonic, SENSOR IS ON
  digitalWrite(pump, LOW);
  digitalWrite(disp, HIGH); //Dispensing indicator 
  
}

Forum_upload_arduino.ino (1.81 KB)

Have you thought of using debug prints?
Or not hijacking unrelated topics?

@VISHNUMK

TOPIC SPLIT
DO NOT HIJACK / NECRO POST !

Could you take a few moments to Learn How To Use The Forum.
Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

@AWOL

yes, i did try serialprint
calculation values are correct

this is what it prints when i have issue actual distance to floor is approx 20cm
but it detects as 19cm,10cm and finally 0 cm...
couldnt find why it is like it