Cirkit Designer LogoCirkit DesignerYour all-in-one circuit design IDE Launch Cirkit Designer App

Arduino UNO Controlled Servo with Ultrasonic Sensor Activation

View and Edit Project In Cirkit DesignerImage of Arduino UNO Controlled Servo with Ultrasonic Sensor Activation

Circuit Documentation

Summary

This circuit is designed to interface an Arduino UNO with an HC-SR04 Ultrasonic Sensor and a Servo motor. The Arduino UNO is powered by a 9V battery and controls the Servo motor based on the distance measurements from the Ultrasonic Sensor. The purpose of the circuit is to detect objects within a certain range and actuate the Servo motor accordingly, which could be used for applications such as opening a lid when an object is detected nearby.

Component List

Arduino UNO

9V Battery

Servo

HC-SR04 Ultrasonic Sensor

Wiring Details

Arduino UNO

9V Battery

Servo

HC-SR04 Ultrasonic Sensor

Documented Code

#include <Servo.h>

const int trigPin = 9;   // Trig pin of Ultrasonic Sensor
const int echoPin = 10;  // Echo pin of Ultrasonic Sensor
Servo myServo;           // Servo motor object
const int servoPin = 6;  // Pin for Servo signal

long duration;
int distance;

void setup() {
  Serial.begin(9600);     // Initialize serial communication at 9600 bps
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  myServo.attach(servoPin);  // Attach servo motor to pin 6
  myServo.write(0);          // Start with the servo at 0 degrees (closed lid)
}

void loop() {
  // Send out ultrasonic pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the time it takes for the pulse to return
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;  // Convert time to distance in cm

  Serial.print("Distance: ");
  Serial.println(distance);

  // If an object is detected within 10 cm, open the lid
  if (distance < 10) {
    myServo.write(90);  // Move to 90 degrees (open lid)
    delay(5000);        // Wait for 5 seconds with the lid open
    myServo.write(0);   // Move back to 0 degrees (close lid)
  }

  delay(500);  // Small delay before next sensor reading
}

The code is written for the Arduino UNO and is responsible for controlling the Servo motor based on the distance measurements from the HC-SR04 Ultrasonic Sensor. The Servo motor is set to move to 90 degrees when an object is detected within 10 cm, indicating an "open lid" position, and then returns to 0 degrees after 5 seconds, indicating a "closed lid" position. The distance is measured by sending an ultrasonic pulse from the TRIG pin and listening for the echo on the ECHO pin. The time it takes for the echo to return is converted into a distance measurement in centimeters.