This is an old revision of the document!
#include <servo.h>
const int trigPin = 6;
const int echoPin = 5;
const int servoPin = 3;
const int MAX_DISTANCE = 50;
const int MIN_DISTANCE = 0;
Servo servo;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo.attach(servoPin);
}
void loop()
{
int duration, distance;
digitalWrite(trigPin, HIGH);
delay(1);
digitalWrite(trigPin, LOW);
// Measure the pulse input in echo pin
duration = pulseIn(echoPin, HIGH);
// Distance is half the duration divided by 29.1
distance = duration / 2 / 29.1;
// if distance less than 0.5 meter and more than 0 (0 or less means over range)
if (distance >= MIN_DISTANCE && distance <= MAX_DISTANCE) {
servo.write(50);
delay(3000);
} else {
servo.write(160);
}
delay(60);
}