This circuit is designed to interface an HC-SR04 Ultrasonic Sensor and a Servo motor with an Arduino UNO microcontroller. The HC-SR04 sensor is used to measure distance, and the Servo motor is controlled based on the distance measurements. The Arduino UNO is programmed to trigger the ultrasonic sensor to send a pulse and then listen for the echo. The time taken for the echo to return is used to calculate the distance to an object. If the measured distance is less than 10 cm, the servo is instructed to move to a 90-degree position. Otherwise, the servo returns to the 0-degree position. The circuit is powered by a 5v Battery.
#include <Servo.h>
#define trigPin 12
#define echoPin 11
Servo servo;
int sound = 250;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo.attach(9);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 10) {
Serial.println("the distance is less than 10");
servo.write(90);
delay(1500);
}
else {
servo.write(0);
}
if (distance > 60 || distance <= 0){
Serial.println("The distance is more than 60");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
This code is written for the Arduino UNO and is responsible for controlling the HC-SR04 Ultrasonic Sensor and the Servo motor. The setup()
function initializes the serial communication, configures the trigger and echo pins, and attaches the servo to pin D9. The loop()
function continuously measures the distance and moves the servo accordingly.