#define IR_SENSOR_PIN D1 // Define the pin connected to the IR sensor OUT
#define RELAY_PIN D2 // Define the pin connected to the relay IN
#define TRIG_PIN D3 // Define the pin connected to the ultrasonic sensor Trig
#define ECHO_PIN D4 // Define the pin connected to the ultrasonic sensor Echo
const int thresholdDistance = 10; // Threshold distance in cm (set based on your glass height)
void setup() {
pinMode(IR_SENSOR_PIN, INPUT); // Set IR sensor pin as input
pinMode(RELAY_PIN, OUTPUT); // Set relay pin as output
pinMode(TRIG_PIN, OUTPUT); // Set ultrasonic sensor Trig pin as output
pinMode(ECHO_PIN, INPUT); // Set ultrasonic sensor Echo pin as input
digitalWrite(RELAY_PIN, LOW); // Initialize the relay to be off
Serial.begin(9600); // Start the serial communication at 115200 baud rate
}
void loop() {
int irValue = digitalRead(IR_SENSOR_PIN); // Read the value from the IR sensor
int distance = measureDistance(); // Measure the distance using the ultrasonic sensor
if (distance <= thresholdDistance && distance > 0) {
// If the water level is at or above the threshold
irValue = HIGH; // Override the IR sensor value to stop the relay
Serial.println("Glass is full, stopping water...");
}
if (irValue == LOW) { // If IR sensor detects an object (LOW output)
digitalWrite(RELAY_PIN, LOW); // Turn on the relay
Serial.println("Object detected! Relay ON.");
} else { // If no object is detected or glass is full
digitalWrite(RELAY_PIN, HIGH); // Turn off the relay
Serial.println("No object detected or glass is full. Relay OFF.");
}
delay(500); // Delay for half a second before repeating the loop
}
int measureDistance() {
// Function to measure the distance using the ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000); // Wait up to 30ms for a valid pulse
if (duration == 0) {
return 0; // Return 0 if no valid echo was received
}
return duration * 0.034 / 2; // Convert the duration to distance in cm
}