This circuit is designed to measure distance using an HC-SR04 Ultrasonic Sensor and display the measured distance on a 16x2 I2C LCD. Additionally, the circuit controls a servo motor, a relay module, an LED, and a piezo speaker based on the measured distance. The Arduino UNO microcontroller is used to manage all the components and execute the embedded code.
Arduino UNO
1 Channel 5V Relay Module
16x2 I2C LCD
Servo
LED: Two Pin (red)
HC-SR04 Ultrasonic Sensor
Resistor
Piezo Speaker
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// Initialize the LCD (I2C address, width, height)
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change I2C address if needed
Servo myServo; // Create a servo object
const int trigPin = 9; // Pin for the Trig
const int echoPin = 10; // Pin for the Echo
const int servoPin = 11; // Pin for the Servo
const int relayPin = 8; // Pin for the Relay
const int ledPin = 7; // Pin for the LED
void setup() {
lcd.begin(); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
lcd.clear(); // Clear any previous content
pinMode(trigPin, OUTPUT); // Set Trig pin as output
pinMode(echoPin, INPUT); // Set Echo pin as input
pinMode(relayPin, OUTPUT); // Set Relay pin as output
pinMode(ledPin, OUTPUT); // Set LED pin as output
myServo.attach(servoPin); // Attach the servo to the pin
Serial.begin(9600); // Start serial communication for debugging
}
void loop() {
// Clear the Trig pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the Trig pin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the Echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
float distance = duration * 0.034 / 2;
// Display the distance on the LCD
lcd.setCursor(0, 0); // Set cursor to first row
lcd.print("Distance: ");
lcd.print(distance); // Print distance
lcd.print(" cm");
// Move the servo and control relay and LED based on distance
if (distance < 10) { // If distance is less than 10 cm
myServo.write(180); // Move servo to 180 degrees
digitalWrite(relayPin, HIGH); // Turn on relay
digitalWrite(ledPin, HIGH); // Turn on LED
} else {
myServo.write(0); // Move servo to 0 degrees
digitalWrite(relayPin, LOW); // Turn off relay
digitalWrite(ledPin, LOW); // Turn off LED
}
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm"); // Print distance to Serial Monitor
delay(500); // Wait for a bit before the next reading
}
This code initializes the LCD, servo, and pins for the ultrasonic sensor, relay, and LED. In the loop
function, it measures the distance using the ultrasonic sensor, displays the distance on the LCD, and controls the servo, relay, and LED based on the measured distance. The distance is also printed to the Serial Monitor for debugging purposes.