#include <EEPROM.h>
#include <Servo.h>
#define echo 2
#define tring 3
Servo myservo;
int pos;
void motor_on();
int flag_m,a,flag=1;
float distance;
void setup() {
Serial.begin(115200);
// a=EEPROM.read(1);
a=1;
// b=EEPROM.read(0);
pinMode(tring, OUTPUT);
pinMode(echo, INPUT);
myservo.attach(9);
}
void loop() {
if(a==1)
{
distance=readDistance();
if(distance>=50)
{
Serial.println(readDistance());
flag_m=1;
EEPROM.write(1,flag_m);
motor_on();
f2();
}
else
{
flag_m=0;
flag=1;
EEPROM.write(1,flag_m);
// motor_off();
Serial.println(readDistance());
}
}
else{
f1();
}
delay(1000);
}
void f1()
{
distance=readDistance();
while(distance>380)
{
Serial.println("motor on!!!");
Serial.println(readDistance());
distance=readDistance();
if(flag==1)
{
flag_m=1;
flag=0;
EEPROM.write(1,flag_m);
motor_on();
}
}
f2();
}
void f2()
{
distance=readDistance();
// flag=0;
while(flag==0 && distance<=380)
{
Serial.println("motor on!!!");
Serial.println(readDistance());
distance=readDistance();
if(distance<30)
{
// motor_off()
flag_m=0;
flag=1;
EEPROM.write(1,flag_m);
}
}
}
void motor_on()
{
for(pos=0;pos<=180;pos++)
{
myservo.write(pos);
delay(15);
}
}
float readDistance()
{
digitalWrite(tring, LOW);
delayMicroseconds(2);
digitalWrite(tring, HIGH);
delayMicroseconds(10);
digitalWrite(tring, LOW);
int duration= pulseIn(echo,HIGH);
return duration*0.034/2;
}