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

Arduino 101 Ultrasonic Distance-Based Servo Controller

View and Edit Project In Cirkit DesignerImage of Arduino 101 Ultrasonic Distance-Based Servo Controller

Circuit Documentation

Summary

This circuit involves an Arduino 101 microcontroller, an HC-SR04 Ultrasonic Sensor, and an MG996R Servo Motor. The ultrasonic sensor measures distance and triggers the servo motor to move when an object is detected within a specified range. The Arduino 101 controls the entire operation, reading the sensor data and driving the servo motor based on the distance measured.

Component List

Arduino 101

HC-SR04 Ultrasonic Sensor

MG996R Servo Motor

Qwiic Cable - Breadboard Jumper (4-pin)

Wiring Details

Arduino 101

HC-SR04 Ultrasonic Sensor

MG996R Servo Motor

Code Documentation

Arduino 101 Code

#include <Servo.h>

const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 3;
const int distanceThreshold = 10; // Distance in cm to trigger the servo

Servo myServo;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  myServo.attach(servoPin);
  myServo.write(0); // Initial position of the servo
  Serial.begin(9600);
}

void loop() {
  long duration, distance;
  
  // Send a 10us pulse to trigger the ultrasonic sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Read the echo pin
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance
  distance = (duration / 2) / 29.1;
  
  // Print the distance to the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
  
  // If the distance is less than the threshold, activate the servo
  if (distance < distanceThreshold) {
    myServo.write(90); // Move the servo to 90 degrees
    delay(1000); // Wait for 1 second
    myServo.write(0); // Move the servo back to 0 degrees
  }
  
  delay(500); // Wait for 0.5 seconds before the next loop
}

This code initializes the pins for the ultrasonic sensor and the servo motor. It continuously measures the distance using the ultrasonic sensor and moves the servo motor to 90 degrees if an object is detected within the specified threshold distance. The servo motor then returns to its initial position after a short delay. The distance measurements are also printed to the Serial Monitor for debugging purposes.