Skip to content

Instantly share code, notes, and snippets.

@danic85
Last active September 10, 2021 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danic85/51f2dd57788ec707504c60c3e48e5669 to your computer and use it in GitHub Desktop.
Save danic85/51f2dd57788ec707504c60c3e48e5669 to your computer and use it in GitHub Desktop.
Arduino Watch Frog (HC-SR04 door distance alarm)
// ---------------------------------------------------------------- //
// Arduino Watch Frog (HC-SR04 door distance alarm)
// Place with sensor facing a closed door and then attach power.
// Alarm will sound if distance to door changes in either direction
// beyond the THRESHOLD. Alarm will not stop until power is disconnected.
// Tested on 10 September 2020
// Author: Dan Nicholson (github.com/danic85)
// ---------------------------------------------------------------- //
#define echoPin 7 // Echo of HC-SR04
#define trigPin 6 // Trig of HC-SR04
#define buzzerPin 4 // Buzzer output
#define ledPin 13 // LED output
#define THRESHOLD 5 // Distance change before sounding alarm (cm)
long duration; // Duration of sound wave travel
int distance; // Distance measurement
int startingDistance; // Initial measurement
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
pinMode(buzzerPin, OUTPUT); // Sets the buzzerPin as an OUTPUT
pinMode(ledPin, OUTPUT); // Sets the ledPin as an OUTPUT
startingDistance = getDistance();
}
void loop() {
delay(500);
if (getDistance() < startingDistance - THRESHOLD || getDistance() > startingDistance + THRESHOLD)
{
// Do this forever!
while (true) {
buzz(HIGH);
delay(500);
buzz(LOW);
delay(500);
}
}
}
int getDistance() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
return distance;
}
void buzz(int val) {
digitalWrite(buzzerPin,val);
digitalWrite(ledPin,val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment