This circuit is designed to control a water pump using an ultrasonic sensor and a relay module, all managed by an Arduino Uno R3. The ultrasonic sensor detects the presence of an object (e.g., a hand) within a certain distance, and if the object is detected, the relay is activated to turn on the water pump. The pump remains on for a specified duration before turning off automatically.
Arduino Uno R3
1 Channel Relay 5V
HC-SR04 Ultrasonic Sensor
Water Pump
Battery 12V
// Ultrasonic Sensor Pins
const int trigPin = 7;
const int echoPin = 6;
// Relay Pin
const int relayPin = 8;
// Threshold Distance (in cm)
const int thresholdDistance = 10;
// Variables to track motor state and time
bool motorState = false; // To track motor ON/OFF state
unsigned long motorStartTime = 0; // To track motor ON duration
bool handDetected = false; // To detect if hand is in range
void setup() {
// Initialize serial monitor
Serial.begin(9600);
// Set up pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
// Ensure relay is off initially (for active LOW relay)
digitalWrite(relayPin, HIGH); // Relay off (HIGH for active LOW relays)
}
void loop() {
// Measure distance
long distance = getDistance();
// Debugging: Print distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if hand is detected
if (distance > 0 && distance <= thresholdDistance) {
if (!handDetected) {
handDetected = true; // Mark hand as detected
motorStartTime = millis(); // Record the time
digitalWrite(relayPin, LOW); // Turn ON motor (LOW for active LOW relay)
motorState = true;
Serial.println("Motor ON");
}
} else {
handDetected = false; // Reset detection when hand is removed
}
// Turn off motor after 3 seconds
if (motorState && millis() - motorStartTime >= 3000) {
digitalWrite(relayPin, HIGH); // Turn OFF motor (HIGH for active LOW relay)
motorState = false;
Serial.println("Motor OFF");
}
delay(100); // Stabilization delay
}
// Function to measure distance using ultrasonic sensor
long getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000); // Timeout to avoid infinite wait
long distance = duration * 0.034 / 2;
return (distance > 0 && distance < 400) ? distance : -1; // Return valid distance
}
This code initializes the pins for the ultrasonic sensor and the relay, measures the distance using the ultrasonic sensor, and controls the relay to turn the water pump on and off based on the measured distance. The pump is turned on when an object is detected within the threshold distance and turned off after 3 seconds.