ARDUINO Ultrasonic Distance or burglar alarm Trip Wire tutorial (HC-SR04)

This tutorial will show you how to set up and use a HC-SR04 ultrasonic device with a ARDUINO board to tell you if you have a burglar (intruder trip line alarm) or you just need to know the distance of a object (car Parking Assistant).

Click on video below for full tutorial.

 

 

ARDUINO CODE:

#define trigPin 9
#define echoPin 10
long duration;
int distance;

void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

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);

if (distance <= 5)
{
tone(3, 500, 500);
delay(500);
tone(3, 800, 500);
delay(500);
}
delay(50);
}