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
}
}
#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
}