#define trigPin 9
#define echoPin 10
long duration;
int distance;
long firstoff;
int distancefirst;
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
delay(1000);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
firstoff = pulseIn(echoPin, HIGH);
distancefirst = firstoff*0.034/2; // cm
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2; // cm
//distance = duration * 0.0133 / 2; // in
Serial.println(distance);
delay(1000);
Serial.println(distancefirst);
if (distance <= distancefirst - 5)
{
tone(3, 500, 500);
delay(500);
tone(3, 800, 500);
delay(500);
delay(50);
}
}
Comments