Introduction: Arduino Control Servo Motor Using Ultrasonic Sensor

Picture of Arduino Control Servo Motor Using Ultrasonic Sensor

In this project you can see how can we control servo motor using arduino and ultrasonic sensor.

How the project work :

when ultrasonic sensor read 5cm distance ore less servo will rotate in 120 degree , else servo will rotate 0 degree

Arduino will print the distance on serial print . You can change the code easy if you need to do other things.

HardwarePut the trigpin of ultrasonic sensor in pin 7 on arduino. Put the echopin of ultrasonic sensor in pin 6 on arduino. Put vcc pin of ultrasinic sensor to 5v on arduino. Put servo to pin 8 on arduino. Put gnd of ultrasonic to gnd on arduino. and connect arduino with Pc.

Code:

#include
#define trigPin 7

#define echoPin 6

Servo servo;

void setup()

{

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

servo.attach(8);

}

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 < 5)

{

Serial.println("the distance is less than 5");

servo.write(120);

}

else

{

servo.write(0);

}

if (distance > 60 || distance <= 0)

{

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

}

else

{

Serial.print(distance);

Serial.println(" cm");

}

delay(500);

}

Comments

About This Instructable

649views

5favorites

License:

Add instructable to: