#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LCD configuration: Adjust the I2C address (0x27 is default, change if necessary)
LiquidCrystal_I2C lcd(0x27, 16, 2); // 0x27 or 0x3F depending on your module
// Pin Definitions
const int trigPin = 25; // GPIO pin connected to the Trig pin of the HC-SR04
const int echoPin = 26; // GPIO pin connected to the Echo pin of the HC-SR04
const int relayPin = 12; // GPIO pin connected to the IN pin of the relay module
// Distance Thresholds in centimeters
const float lowLevelThreshold = 10.0; // Distance below which to turn on the relay
const float highLevelThreshold = 20.0; // Distance above which to turn off the relay
void setup() {
// Initialize Serial Monitor at 115200 baud rate
Serial.begin(115200);
// Initialize the LCD
lcd.init(); // initialize the lcd// Initialize the 16x2 LCD
lcd.backlight(); // Turn on the LCD backlight
// Clear the LCD screen
// Pin setups
pinMode(trigPin, OUTPUT); // Set Trig pin as OUTPUT
pinMode(echoPin, INPUT); // Set Echo pin as INPUT
pinMode(relayPin, OUTPUT); // Set Relay pin as OUTPUT
digitalWrite(relayPin, LOW); // Ensure the relay is off initially
}
void loop() {
long duration;
float distance;
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse from the Echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = (duration * 0.0344) / 2.0;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Display distance on the LCD
lcd.setCursor(0, 1); // Set cursor to the second line for distance
lcd.print("Dist: ");
lcd.print(distance);
lcd.print(" cm "); // Add extra spaces to overwrite old data
// Control the relay based on the distance
if (distance < lowLevelThreshold) {
// Turn on the relay if distance is below the low threshold
digitalWrite(relayPin, HIGH);
lcd.setCursor(10, 1); // Update LCD to show relay status on the right
lcd.print("ON ");
Serial.println("Relay ON");
}
else if (distance > highLevelThreshold) {
// Turn off the relay if distance is above the high threshold
digitalWrite(relayPin, LOW);
lcd.setCursor(10, 1); // Update LCD to show relay status on the right
lcd.print("OFF");
Serial.println("Relay OFF");
}
// Wait before the next measurement
delay(1000);
}