Arduino “having11” Guy
Published © GPL3+

Monitor Your Front Door

Use a SparkFun ESP8266 Thing Dev and HC-SR04 to create a monitoring device that can make sure your door stays closed while you're away.

EasyFull instructions provided1 hour3,061
Monitor Your Front Door

Things used in this project

Hardware components

SparkFun ESP8266 Thing - Dev Board
SparkFun ESP8266 Thing - Dev Board
×1
Ultrasonic Sensor - HC-SR04
SparkFun Ultrasonic Sensor - HC-SR04
×1
USB Li Ion Battery Charger
Adafruit USB Li Ion Battery Charger
Optional
×1
1000 mAh Lithium Ion Battery
Optional
×1

Software apps and online services

Cayenne
myDevices Cayenne
Arduino IDE

Story

Read more

Schematics

Schematic

Code

ESP8266 Code

C/C++
You must include your credentials and make sure the channels match up to your Cayenne widgets!
//Door Monitor

/* Wiring:
 *  
 *  ESP8266 | HC-SR04
 *  12      | Trig
 *  13      | Echo
 *  5v      | VCC
 *  GND     | GND
 *  
 */

#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>

const int trigPin = 12;
const int echoPin = 13;
const int ledPin = 4;

// WiFi network info.
char ssid[] = "SSID";
char wifiPassword[] = "PASS";

// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "USERNAME";
char password[] = "PASSWORD";
char clientID[] = "CLIENT-ID";

long howOften = 10 * 1000; //How often to take reading in milliseconds
unsigned long lastReading = 0; //Keep track of when the last reading was taken
long distance;

bool is_active = false; //Know if the device is to take readings

void setup() {
  Serial.begin(9600);
  Cayenne.begin(username, password, clientID, ssid, wifiPassword);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  Cayenne.loop();

  if(is_active){
    if(millis()-lastReading > howOften){
      distance = takeReading();
      Serial.println("Distance: "+String(distance)+"cm");
      Cayenne.virtualWrite(V1, distance);
      lastReading = millis();
    }
  }
}

long takeReading(){
  
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);

  return duration / 29 /2; //Distance in cm
  
}

CAYENNE_IN(2){
  String value = getValue.asString();
  if(value=="1"){
    is_active = true;
    Serial.println("Armed");
    digitalWrite(ledPin, HIGH);
  }
  else{
    is_active = false;
    Serial.println("Disarmed");
    Cayenne.virtualWrite(V1, 500); //So it won't falsely trigger
    digitalWrite(ledPin, LOW);
  }
}

Credits

Arduino “having11” Guy

Arduino “having11” Guy

51 projects • 296 followers
IoT, Arduino, and Raspberry Pi. I can create designs, code, and build projects for only $22/hr. Just message me with your project request.

Comments