#include <Servo.h>
#define PIN_TRIG 3
#define PIN_ECHO 2
#define SERVO_PIN 11
Servo servo;
const int open = 90;
const int close = 0;
const int threshold = 75;
long lastUpdate = 0;
const int updateInterval = 200;
//function that returns distance in inches
int distance(){
digitalWrite(PIN_TRIG,HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG,LOW);
int duration = pulseIn(PIN_ECHO,HIGH);
//printing distance in inches
int distance = duration/148;
Serial.print("Distance in inches: ");
Serial.println(distance);
return distance;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(PIN_TRIG,OUTPUT);
pinMode(PIN_ECHO,INPUT);
servo.attach(SERVO_PIN);
servo.write(close);
}
void loop() {
// put your main code here, to run repeatedly:
if(millis()-lastUpdate >= updateInterval){
lastUpdate = millis();
int dis = distance();
if(dis<=75){
servo.write(open);
}else{
servo.write(close);
}
}
}