// YWROBOT
// Compatible with the Arduino IDE 1.0
// Library version:1.1
#define TRIG_PIN 3
#define ECHO_PIN 2
#define LED_RED 13
#define LED_GREEN 12
#define SWITCH_PIN 8 // Switch pin for turning the device on/off
#define VALVE_PIN 11 // Valve control pin
const int hands_present_threshold = 20; // Threshold distance in cm
const unsigned long DETECTION_TIME = 3000; // 10 seconds in milliseconds
unsigned long detectionStartTime = 0; // Tracks when detection starts
bool isDetecting = false; // Tracks if hands are currently detected
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_RED, OUTPUT);
pinMode(SWITCH_PIN, INPUT_PULLUP); // Use internal pull-up resistor for the switch
pinMode(VALVE_PIN, OUTPUT); // Set valve pin as output
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
digitalWrite(VALVE_PIN, LOW); // Ensure valve is initially off
Serial.begin(9600);
}
void loop() {
// Check if the switch is ON
if (digitalRead(SWITCH_PIN) == LOW) {
long duration, distance;
// Trigger the HC-SR04
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the echo duration
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
// Debugging output
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if hands are within range
if (distance > 0 && distance <= hands_present_threshold) {
if (!isDetecting) {
// Start detection process
detectionStartTime = millis();
isDetecting = true;
// Turn on red LED and open the valve
digitalWrite(LED_RED, HIGH);
digitalWrite(VALVE_PIN, HIGH);
} else if (millis() - detectionStartTime >= DETECTION_TIME) {
// Hands have been detected for 10 seconds
isDetecting = false;
// Turn off red LED, close the valve, and turn on green LED
digitalWrite(LED_RED, LOW);
digitalWrite(VALVE_PIN, LOW);
digitalWrite(LED_GREEN, HIGH);
}
} else {
// If hands are out of range, reset
isDetecting = false;
detectionStartTime = 0;
// Turn off red LED, green LED, and valve
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
digitalWrite(VALVE_PIN, LOW);
}
delay(100); // Small delay for stability
} else {
// If the switch is OFF, turn everything off
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
digitalWrite(VALVE_PIN, LOW);
isDetecting = false; // Reset detection
detectionStartTime = 0; // Reset timer
}
}