Controlling a Servo With an Ultrasonic Sensor Using Arduino

by LevinCharles in Circuits > Arduino

53240 Views, 8 Favorites, 0 Comments

Controlling a Servo With an Ultrasonic Sensor Using Arduino

Intro.PNG

We are a group of UQD10801 (Robocon1) students from Universiti Tun Hussein Onn Malaysia (UTHM) that will demonstrate how to control a servo motor using an ultrasonic sensor and an arduino as part of our assignment.

An ultrasonic sensor is a device that can measure the distance to an object by the use of sound waves while a servo motor is built for precision control of the angular or linear position, velocity, and acceleration.

Step 1: Components Needed

Components.PNG

1) Arduino Uno x 1

2) Ultrasonic Sensor x 1

3) Servo Motor x 1

4) Breadboard

Step 2: Platform Used

tinkercad-logo.png

The platform used to build the circuit and test the simulation was Tinkercad.

Step 3: the Working Principle

How does it work.PNG

The servo motor will rotate to a certain angle depending on the distance detected by the ultrasonic sensor. The distance detected will also be displayed on the serial monitor.

Step 4: Connection (Ultrasonic Sensor)

connection (US).PNG

1) Connect the 5V pin of the Arduino board to the bottom row of the breadboard
2) Connect the GND pin to the top row of the breadboard.

3) Connect the VCC pin of the sensor to the positive terminal of the breadboard.

4) Connect the GND pin to the negative terminal of the breadboard.

5) Connect the TRIG to pin 9 of the Arduino.

6) Connect the ECHO pin to pin 8 of the Arduino

Step 5: Connection (Servo Motor)

connection (SM).PNG

1) Connect the positive terminal/power to the positive terminal of breadboard.

2) Connect the ground terminal of servo motor to the negative terminal of the breadboard.

3) Connect the data wire/ signal to pin 6 of the Arduino board.

Step 6: Coding

#include <Servo.h>

#define trigPin 9

#define echoPin 8

Servo servo;

int sound = 250;

void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

servo.attach(6);

}

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 < 80) {

Serial.print(distance);

Serial.println(" cm");

servo.write(90);

}

else if (distance<180) {

Serial.print(distance);

Serial.println(" cm");

servo.write(180); }

else {

Serial.println("The distance is more than 180cm");

}

delay(500);

}

Tutorial Video

Ultrasonic and Servo Motor Control (Tutorial 1)

This video is made for better understanding of the overall process.