1
2
3
4#include <Servo.h>
5#define echoPin 14
6#define trigPin 12
7#define motor 2
8Servo myservo;
9
10long duration;
11int distance;
12void setup()
13{
14 Serial.begin(9600);
15 pinMode(trigPin,OUTPUT);
16 pinMode(echoPin,INPUT);
17 pinMode(motor,OUTPUT);
18 myservo.attach(5,500,2500);
19
20}
21void loop()
22{
23 digitalWrite(trigPin,LOW);
24 delayMicroseconds(2);
25 digitalWrite(trigPin,HIGH);
26 delayMicroseconds(10);
27 digitalWrite(trigPin,LOW);
28 duration=pulseIn(echoPin,HIGH);
29 distance=(duration*0.034/2);
30 Serial.print("Distance : ");
31 Serial.print(distance);
32 Serial.println(" cm ");
33 delay(100);
34
35 if (distance <=50)
36 {
37 digitalWrite(motor,LOW);
38 delay(1000);
39 myservo.write(180);
40 delay(2000);
41 digitalWrite(motor,HIGH);
42 delay(1500);
43 myservo.write(0);
44 delay(1000);
45 }
46
47 else
48 digitalWrite(motor,HIGH);
49}
50