Introduction: Controlling a Servo With an Ultrasonic Sensor Using Arduino
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: Step 1: Components Needed
1) Arduino Uno x 1
2) Ultrasonic Sensor x 1
3) Servo Motor x 1
4) Breadboard
Step 2: Step 2: Platform Used
The platform used to build the circuit and test the simulation was Tinkercad.
Step 3: Step 3: the Working Principle
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: Step 4: Connection (Ultrasonic Sensor)
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: Step 5: Connection (Servo Motor)
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: 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);
}
Step 7: Tutorial Video
This video is made for better understanding of the overall process.