#define TRIG_PIN 13
#define ECHO_PIN 12
#define IND_LED 11
#define BUZ_PIN 9
bool entered;
long duration, distance;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(IND_LED, OUTPUT);
pinMode(BUZ_PIN, OUTPUT);
entered = false;
}
void loop() {
// put your main code here, to run repeatedly:
// Clear sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Generate 10 microseconds pulse to the sensor
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH); // in microseconds
distance = (duration / 2) / 29.1; // in cm
// Assuming door width is 10cm (If someone crossed the 10cm range, alarm will be raised)
if (distance < 10) {
entered = true;
}
// Alarm raises when someone crossed the range
if (entered) {
// Turn on alarm light
digitalWrite(IND_LED, HIGH);
// Generate 2KHz buzzer noise
tone(BUZ_PIN, 2000);
delay(500);
digitalWrite(IND_LED, LOW);
noTone(BUZ_PIN);
}
Serial.print(distance);
Serial.println(" cm");
delay(500);
}