This circuit utilizes an Arduino UNO microcontroller to control an HC-SR04 Ultrasonic Sensor, a red LED, a micro servo motor, and a buzzer. The ultrasonic sensor measures distance, and based on the distance, the microcontroller controls the servo motor, LED, and buzzer. If an object is detected within 10 cm, the servo rotates to 90 degrees, the LED lights up, and the buzzer sounds. Otherwise, the servo resets to 0 degrees, the LED turns off, and the buzzer is silent.
Arduino UNO
LED: Two Pin (red)
HC-SR04 Ultrasonic Sensor
Micro servo 9G
Buzzer
5V connected to:
GND connected to:
D9 connected to:
D8 connected to:
D5 connected to:
D4 connected to:
D3 connected to:
cathode connected to:
anode connected to:
VCC connected to:
TRIG connected to:
ECHO connected to:
GND connected to:
GND connected to:
+5V connected to:
PWM connected to:
PIN connected to:
GND connected to:
#include <Servo.h>
// Define pins for HC-SR04
const int trigPin = 9;
const int echoPin = 8;
// Define pins for buzzer and LED
const int buzzerPin = 4;
const int ledPin = 5;
// Define variables for duration and distance
long duration;
int distance;
// Create servo object
Servo myServo;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
// Attach servo to pin 3
myServo.attach(3);
// Initialize servo position and outputs
myServo.write(0);
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);
}
void loop() {
// Send a 10-microsecond pulse to the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and calculate the distance
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Convert to cm
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Control servo, buzzer, and LED based on distance
if (distance < 10) {
myServo.write(90); // Rotate servo to 90 degrees
digitalWrite(buzzerPin, HIGH); // Activate buzzer
digitalWrite(ledPin, HIGH); // Turn on LED
Serial.println("Object detected: Servo at 90 degrees, Buzzer ON, LED ON");
} else {
myServo.write(0); // Reset servo to 0 degrees
digitalWrite(buzzerPin, LOW); // Deactivate buzzer
digitalWrite(ledPin, LOW); // Turn off LED
Serial.println("No object: Servo at 0 degrees, Buzzer OFF, LED OFF");
}
// Small delay for stability
delay(200);
}
This code initializes the pins and components in the setup()
function and continuously measures the distance using the HC-SR04 sensor in the loop()
function. Based on the measured distance, it controls the servo motor, LED, and buzzer.