Created by
KATAKAM GANESH
| #include <Servo.h> //servo library
Servo servo;
int trigPin = 5; // the pins 5,6 the Ultrasonic sensor is attached to
int echoPin = 6;
int servoPin = 7; //the pin that Servomotor is atttached to
long duration, dist, average;
long aver[3]; //array for average
void setup()
{
Serial.begin(9600);
servo.attach(servoPin);
pinMode(trigPin, OUTPUT); //sets the trigpin as output
pinMode(echoPin, INPUT); // sets the echopin as input
servo.write(0);
delay(100); //delay for 100 milli sec
servo.detach();
}
void measure()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(15);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
dist = (duration*0.034) / 2; //obtain distance
}
void loop()
{
for (int i=0;i<=2;i++) //average distance
{
measure();
aver[i]=dist;
delay(10); //delay between measurements
}
dist=(aver[0]+aver[1]+aver[2])/3;
if ( dist<50 )
{
servo.attach(servoPin);
delay(1);
servo.write(0);
delay(3000);
servo.write(150);
delay(1000);
servo.detach();
}
Serial.print(dist);
}
|