#include <Servo.h>
#define trig 8
#define echo 7
long pul_echo;
float dis;
int flag = 1;
int sw = 5;
Servo servo1;
unsigned int val;
void setup()
{
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
servo1.attach(9, 500, 2500);
pinMode(sw, INPUT_PULLUP);
Serial.begin(9600);
}
void loop(){
if(digitalRead(sw)==0&&flag== 1){
while(digitalRead(sw)==0);
flag = 0;
}
if(digitalRead(sw)==0&&flag == 3){
while(digitalRead(sw)==0);
flag = 1;
}
if(flag==0){
servo1.write(45);
delay(2000);
servo1.write(0);
delay(500);
flag=3;
}
Serial.println(flag);
if(flag==1){
digitalWrite(trig,0);
delay(10);
digitalWrite(trig,1);
delayMicroseconds(10);
digitalWrite(trig,0);
pul_echo = pulseIn(echo,1);
dis = (pul_echo/2.0)/29.0;
if(dis<50){
servo1.write(45);
}
else if(dis>50){
servo1.write(0);
}
}
}