#define TRIG_PIN 2
#define ECHO_PIN 3
#define PUMP_PIN 4
#define BUTTON_PIN 5
bool glassDetected = false;
bool manualStop = false;
unsigned long lastDetectionTime = 0;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(PUMP_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
long duration, distance;
// Check if the manual stop button is pressed
if (digitalRead(BUTTON_PIN) == LOW) {
manualStop = true;
digitalWrite(PUMP_PIN, LOW); // Turn off the pump
} else {
manualStop = false;
}
// If manual stop is active, exit loop
if (manualStop) {
return;
}
// Clear the trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to trigger the sensor
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the pulse from the echo pin
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than a threshold (adjust as needed)
if (distance < 10) {
if (!glassDetected) {
// Activate the pump
digitalWrite(PUMP_PIN, HIGH);
lastDetectionTime = millis(); // Record the time of glass detection
glassDetected = true;
} else {
// Check if 4 seconds have passed since the last detection
if (millis() - lastDetectionTime >= 4000) {
digitalWrite(PUMP_PIN, LOW); // Turn off the pump
}
}
} else {
glassDetected = false;
digitalWrite(PUMP_PIN, LOW); // Ensure the pump is off when no glass is detected
}
// Delay before the next reading
delay(100);
}