

This circuit is designed to interface an ESP32 microcontroller with several peripherals: an I2C LCD 16x2 screen, an HC-SR04 Ultrasonic Distance Sensor, and a 2-Channel Relay Module. The ESP32 is responsible for measuring distance using the ultrasonic sensor, displaying the measurement on the LCD screen, and controlling the relay module based on the distance detected. The relay module can switch external devices or circuits on or off depending on the sensor's output.
/*
* This Arduino Sketch interfaces an ESP32 with an I2C LCD 16x2 screen,
* an HC-SR04 Ultrasonic Distance Sensor, and a 2-Channel Relay Module.
* The ESP32 displays distance measurements on the LCD screen and controls
* the relay based on the distance measured by the ultrasonic sensor.
* Connections:
* - ESP32 GND to LCD GND, Relay GND, Ultrasonic Sensor GND
* - ESP32 Vin to LCD VCC (5V), Relay VCC, Ultrasonic Sensor VCC
* - ESP32 D22 to LCD SCL
* - ESP32 D21 to LCD SDA
* - ESP32 D33 to Ultrasonic Sensor TRIG
* - ESP32 D26 to Ultrasonic Sensor ECHO
* - ESP32 VP to Relay IN1
* - ESP32 VN to Relay IN2
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define TRIG_PIN 33
#define ECHO_PIN 26
#define RELAY1_PIN 36 // VP
#define RELAY2_PIN 39 // VN
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
lcd.print("Initializing...");
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RELAY1_PIN, OUTPUT);
pinMode(RELAY2_PIN, OUTPUT);
digitalWrite(RELAY1_PIN, LOW);
digitalWrite(RELAY2_PIN, LOW);
delay(2000);
lcd.clear();
}
void loop() {
long duration, distance;
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2) / 29.1;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
if (distance < 10) {
digitalWrite(RELAY1_PIN, HIGH);
digitalWrite(RELAY2_PIN, LOW);
} else if (distance < 20) {
digitalWrite(RELAY1_PIN, LOW);
digitalWrite(RELAY2_PIN, HIGH);
} else {
digitalWrite(RELAY1_PIN, LOW);
digitalWrite(RELAY2_PIN, LOW);
}
delay(1000);
}
This code initializes the connected devices and enters a loop where it measures distance using the ultrasonic sensor, displays the result on the LCD, and controls the relay module based on the measured distance. The relay logic is set to activate one relay if the distance is less than 10 cm, another if the distance is between 10 and 20 cm, and turn off both if the distance is greater than 20 cm.