Have you ever wanted a low-cost door sensor that emails you when your door opens? Well, that's what I'm going to show you how to make. Let's get started!
Parts List
- ESP8266 development board (link to one I found on Amazon)
- Alligator clips
- Magnet
- Reed switch
- 10KΩ resistor
- A few wires :)
- Micro USB data cable, NOT CHARGING CABLE!
- Power source
First, go to one of my other ESP8266 tutorials if you have not worked with an ESP8266 in the Arduino IDE yet to install the IDE and the driver and run the "Blink" program. Don't worry, we'll wait for you.
Now, let's start.
First, go to Adafruit IO and make an Adafruit account.
Then log in to Adafruit IO and create a dashboard (go into Your Dashboards->Create Dashboard) and call it whatever you want. (maybe Door Sensors or something)
See the blue "+" button? Click it.
You should see this:
First, go to Adafruit IO and make an Adafruit account.
Then log in to Adafruit IO and create a dashboard (go into Your Dashboards->Create Dashboard) and call it whatever you want. (maybe Door Sensors or something)
See the blue "+" button? Click it.
You should see this:
See the blue "Create" button under "A text block can be used to send data as well as view data."? Click it. You should see this:
See the blue "Create" button to the right of the "NEW FEED NAME" text box? Enter "sidedoor" into the text box and hit "Create". (You could type something instead of "sidedoor", but in the code, your sensor will post to the "sidedoor" feed if you do not modify it.)
Now you should see your Adafruit username next to a plus sign. Click the plus sign. See all those "Choose" buttons? Click the "Choose" button next to "sidedoor". Then click "NEXT STEP >". You should see this:
Click "CREATE BLOCK".
Here is what you do next (images below are from https://learn.adafruit.com/using-ifttt-with-adafruit-io/ifttt-to-adafruit-io-setup):
Select the "sidedoor" feed from the menu "and make the relationship" (from same site as images) not equal to "______________" (literally put 14 underlines in). Click "Create Trigger". Then press the "that" link and configure it to email you (images below from https://learn.adafruit.com/using-ifttt-with-adafruit-io/ifttt-to-adafruit-io-setup):
Now you're done... with the emailing part of the project. ;)
This is how to build the circuit:
This is how to build the circuit:
The green thing is the reed switch. Finished building yet? If you are, the code is here:
/***************************************************
Adafruit MQTT Library ESP8266 Example
Must use ESP8266 Arduino from:
https://github.com/esp8266/Arduino
Works great with Adafruit's Huzzah ESP board & Feather
----> https://www.adafruit.com/product/2471
----> https://www.adafruit.com/products/2821
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <EEPROM.h>
#define SLEEPYTIME 4 // in seconds
String esttime;
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
unsigned int localPort = 2390; // local port to listen for UDP packets
/* Don't hardwire the IP address or we won't get the benefits of the pool.
* Lookup the IP address for the host name instead */
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;
/************************* WiFi Access Point *********************************/
#define WLAN_SSID "your-wifi-username"
#define WLAN_PASS "your-wifi-password"
#define ESP_SSID "configuration-wifi-username"
#define ESP_PASS "configuration-wifi-password"
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "your-Adafruit-username"
#define AIO_KEY "your-AIO-Key"
#define FEED "your-Adafruit-username/f/sidedoor"
/************ Global State (you don't need to change this!) ******************/
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
WiFiServer server(80);
int activater = 1;
int twentyfour = 0;
int twelve = 1;
int transmit = 1;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM = AIO_KEY;
const char DOOR[] PROGMEM = FEED;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);
Adafruit_MQTT_Publish da_door(&mqtt, DOOR);
/****************************** Feeds ***************************************/
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
// Setup a feed called 'onoff' for subscribing to changes.
/*************************** Sketch Code ************************************/
// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();
unsigned long sendNTPpacket(IPAddress& address)
{
Serial.println("sending NTP packet...");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
udp.beginPacket(address, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
}
void setup() {
Serial.begin(115200);
pinMode(14, INPUT); // D5--(Normally Open reed switch)--3V3
delay(10);
Serial.println(F("Side Door Monitor"));
delay(10);
ESP.wdtFeed();
EEPROM.begin(4);
ESP.wdtFeed();
Serial.println("Connecting to your WiFi network...");
WiFi.mode(WIFI_AP_STA);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
yield();
delay(500);
}
Serial.println("Connected");
Serial.println();
WiFi.softAP(ESP_SSID, ESP_PASS);
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
server.begin();
Serial.println("Server started");
Serial.println("Starting UDP");
udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(udp.localPort());
WiFi.hostByName(ntpServerName, timeServerIP);
ESP.wdtFeed();
// Check if a client has connected
}
uint32_t x=0;
void loop(){
String timestatus = "Currently set to ";
twelve = EEPROM.read(0); // twelve, twentyfour, activater
twentyfour = EEPROM.read(1);
activater = EEPROM.read(2);
if (twelve == 1) {
timestatus += "twelve hour time.";
}
else {
timestatus += "twenty-four hour time.";
}
WiFiClient client = server.available();
boolean noclient = false;
if (!client) {
yield();
noclient = true;
}
if (noclient != true) {
// Wait until the client sends some data
Serial.println("new client");
unsigned long start = millis();
unsigned long stopper = millis();
while(!client.available()){
delay(1);
yield();
stopper = millis();
if ((stopper-start) >= 15000) {
break;
}
}
// Read the first line of the request
String req = client.readString();
Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf("192.168.4.1") != -1) {
if (req.indexOf("/your-activate-and-deactivate-page") != -1) {
twelve = EEPROM.read(0); // twelve, twentyfour, activater
twentyfour = EEPROM.read(1);
activater = EEPROM.read(2);
String activaterstring = "";
if (activater == 1) {
activaterstring = "Currently activated.";
}
else {
activaterstring = "Currently deactivated.";
}
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><a href='/your-activater-page'>Activate</a><br><a href='/your-deactivater-page'>Deactivate</a><br/>"+activaterstring+"</html>");
}
else if (req.indexOf("/your-home-page") != -1) {
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><a href='/your-12-hour-page'>12 Hour Time</a><br><a href='/your-24-hour-page'>24 Hour Time</a><br/>"+timestatus+"</html>");
}
else if (req.indexOf("/your-12-hour-page") != -1) {
twentyfour = 0;
twelve = 1;
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Set to 12 hour time</p><a href='/your-home-page'>Home</a></html>");
writeVarData();
}
else if (req.indexOf("/your-24-hour-page") != -1) {
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Set to 24 hour time</p><a href='/your-home-page'>Home</a></html>");
twentyfour = 1;
twelve = 0;
writeVarData();
}
else if (req.indexOf("/your-activater-page") != -1) {
activater = 1;
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Activated</p><a href='/your-activater-page'>Activate</a><br><a href='/your-deactivater-page'>Deactivate</a><br><a href='/your-home-page'>Home Page</a></html>");
writeVarData();
}
else if (req.indexOf("/your-deactivater-page") != -1) {
activater = 0;
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Deactivated</p><a href='/your-activater-page'>Activate</a><br><a href='/your-deactivater-page'>Deactivate</a><br><a href='/your-home-page'>Home Page</a></html>");
writeVarData();
}
else {
Serial.println("invalid request");
client.stop();
}
}
else {
Serial.println("Request not from ESP-made AP, sending 403 Forbidden");
client.print("HTTP/1.1 403 Forbidden");
}
}
client.flush();
delay(1);
twelve = EEPROM.read(0); // twelve, twentyfour, activater
twentyfour = EEPROM.read(1);
activater = EEPROM.read(2);
sendNTPpacket(timeServerIP); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
int cb = udp.parsePacket();
if (!cb) {
Serial.println("no packet yet");
esttime = "not available";
}
else {
Serial.print("packet received, length=");
Serial.println(cb);
// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
int hour = (epoch % 86400L) / 3600;
hour = hour-4;
int minute = (epoch % 3600) / 60;
int second = epoch % 60;
String ampm = " AM";
if (twelve == 1) {
if (hour > 12) {
hour -= 12;
ampm = " PM";
}
if (hour == 0) {
hour = 12;
}
}
esttime = String(hour) + ':'; // + String(minute) + ':' + String(second);
if (minute < 10) {
esttime += '0' + String(minute) + ':';
}
else {
esttime += String(minute) + ':';
}
if (second < 10) {
esttime += '0' + String(second);
}
else {
esttime += String(second);
}
if (twelve == 1) {
esttime += ampm;
}
// print the hour, minute and second:
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch % 60); // print the second
Serial.print("EST Time: ");
Serial.println(esttime);
}
// Setup MQTT subscription for onoff & slider feed.
ESP.wdtFeed();
MQTT_connect();
Serial.println("Signal Strength is " + String(WiFi.RSSI()));
Adafruit_MQTT_Subscribe *subscription;
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
if (digitalRead(14) == LOW) {
Serial.println("Door open");
if (activater == 1) {
Serial.println("Transmitting unlocked message");
String first = String("SIDE DOOR UNLOCKED!") + String(" EST Time is ") + esttime;
char message[50];
first.toCharArray(message, 50);
transmit = 1;
da_door.publish(message);
delay(2000);
}
else {
Serial.println("Door open, but not activated");
if (transmit == 1) {
da_door.publish("______________");
delay(2000);
transmit = 0;
}
}
}
if (digitalRead(14) == HIGH) {
Serial.println("Door closed");
if (transmit == 1) {
da_door.publish("______________");
delay(2000);
transmit = 0;
}
}
// ping the server to keep the mqtt connection alive
if(! mqtt.ping()) {
mqtt.disconnect();
}
ESP.wdtFeed();}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 5;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
char *readFromEEPROM(uint64_t sizevar) {
size_t i;
char *data = "";
for(i=0; i<=sizevar; i++)
{
data[i] = EEPROM.read(i);
}
return data;
}
void writeVarData() {
EEPROM.write(0, twelve);
EEPROM.write(1, twentyfour);
EEPROM.write(2, activater);
EEPROM.commit();
}
Adafruit MQTT Library ESP8266 Example
Must use ESP8266 Arduino from:
https://github.com/esp8266/Arduino
Works great with Adafruit's Huzzah ESP board & Feather
----> https://www.adafruit.com/product/2471
----> https://www.adafruit.com/products/2821
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <EEPROM.h>
#define SLEEPYTIME 4 // in seconds
String esttime;
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
unsigned int localPort = 2390; // local port to listen for UDP packets
/* Don't hardwire the IP address or we won't get the benefits of the pool.
* Lookup the IP address for the host name instead */
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;
/************************* WiFi Access Point *********************************/
#define WLAN_SSID "your-wifi-username"
#define WLAN_PASS "your-wifi-password"
#define ESP_SSID "configuration-wifi-username"
#define ESP_PASS "configuration-wifi-password"
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "your-Adafruit-username"
#define AIO_KEY "your-AIO-Key"
#define FEED "your-Adafruit-username/f/sidedoor"
/************ Global State (you don't need to change this!) ******************/
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
WiFiServer server(80);
int activater = 1;
int twentyfour = 0;
int twelve = 1;
int transmit = 1;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM = AIO_KEY;
const char DOOR[] PROGMEM = FEED;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);
Adafruit_MQTT_Publish da_door(&mqtt, DOOR);
/****************************** Feeds ***************************************/
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
// Setup a feed called 'onoff' for subscribing to changes.
/*************************** Sketch Code ************************************/
// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();
unsigned long sendNTPpacket(IPAddress& address)
{
Serial.println("sending NTP packet...");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
udp.beginPacket(address, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
}
void setup() {
Serial.begin(115200);
pinMode(14, INPUT); // D5--(Normally Open reed switch)--3V3
delay(10);
Serial.println(F("Side Door Monitor"));
delay(10);
ESP.wdtFeed();
EEPROM.begin(4);
ESP.wdtFeed();
Serial.println("Connecting to your WiFi network...");
WiFi.mode(WIFI_AP_STA);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
yield();
delay(500);
}
Serial.println("Connected");
Serial.println();
WiFi.softAP(ESP_SSID, ESP_PASS);
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
server.begin();
Serial.println("Server started");
Serial.println("Starting UDP");
udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(udp.localPort());
WiFi.hostByName(ntpServerName, timeServerIP);
ESP.wdtFeed();
// Check if a client has connected
}
uint32_t x=0;
void loop(){
String timestatus = "Currently set to ";
twelve = EEPROM.read(0); // twelve, twentyfour, activater
twentyfour = EEPROM.read(1);
activater = EEPROM.read(2);
if (twelve == 1) {
timestatus += "twelve hour time.";
}
else {
timestatus += "twenty-four hour time.";
}
WiFiClient client = server.available();
boolean noclient = false;
if (!client) {
yield();
noclient = true;
}
if (noclient != true) {
// Wait until the client sends some data
Serial.println("new client");
unsigned long start = millis();
unsigned long stopper = millis();
while(!client.available()){
delay(1);
yield();
stopper = millis();
if ((stopper-start) >= 15000) {
break;
}
}
// Read the first line of the request
String req = client.readString();
Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf("192.168.4.1") != -1) {
if (req.indexOf("/your-activate-and-deactivate-page") != -1) {
twelve = EEPROM.read(0); // twelve, twentyfour, activater
twentyfour = EEPROM.read(1);
activater = EEPROM.read(2);
String activaterstring = "";
if (activater == 1) {
activaterstring = "Currently activated.";
}
else {
activaterstring = "Currently deactivated.";
}
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><a href='/your-activater-page'>Activate</a><br><a href='/your-deactivater-page'>Deactivate</a><br/>"+activaterstring+"</html>");
}
else if (req.indexOf("/your-home-page") != -1) {
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><a href='/your-12-hour-page'>12 Hour Time</a><br><a href='/your-24-hour-page'>24 Hour Time</a><br/>"+timestatus+"</html>");
}
else if (req.indexOf("/your-12-hour-page") != -1) {
twentyfour = 0;
twelve = 1;
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Set to 12 hour time</p><a href='/your-home-page'>Home</a></html>");
writeVarData();
}
else if (req.indexOf("/your-24-hour-page") != -1) {
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Set to 24 hour time</p><a href='/your-home-page'>Home</a></html>");
twentyfour = 1;
twelve = 0;
writeVarData();
}
else if (req.indexOf("/your-activater-page") != -1) {
activater = 1;
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Activated</p><a href='/your-activater-page'>Activate</a><br><a href='/your-deactivater-page'>Deactivate</a><br><a href='/your-home-page'>Home Page</a></html>");
writeVarData();
}
else if (req.indexOf("/your-deactivater-page") != -1) {
activater = 0;
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML><html><p>Deactivated</p><a href='/your-activater-page'>Activate</a><br><a href='/your-deactivater-page'>Deactivate</a><br><a href='/your-home-page'>Home Page</a></html>");
writeVarData();
}
else {
Serial.println("invalid request");
client.stop();
}
}
else {
Serial.println("Request not from ESP-made AP, sending 403 Forbidden");
client.print("HTTP/1.1 403 Forbidden");
}
}
client.flush();
delay(1);
twelve = EEPROM.read(0); // twelve, twentyfour, activater
twentyfour = EEPROM.read(1);
activater = EEPROM.read(2);
sendNTPpacket(timeServerIP); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
int cb = udp.parsePacket();
if (!cb) {
Serial.println("no packet yet");
esttime = "not available";
}
else {
Serial.print("packet received, length=");
Serial.println(cb);
// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
int hour = (epoch % 86400L) / 3600;
hour = hour-4;
int minute = (epoch % 3600) / 60;
int second = epoch % 60;
String ampm = " AM";
if (twelve == 1) {
if (hour > 12) {
hour -= 12;
ampm = " PM";
}
if (hour == 0) {
hour = 12;
}
}
esttime = String(hour) + ':'; // + String(minute) + ':' + String(second);
if (minute < 10) {
esttime += '0' + String(minute) + ':';
}
else {
esttime += String(minute) + ':';
}
if (second < 10) {
esttime += '0' + String(second);
}
else {
esttime += String(second);
}
if (twelve == 1) {
esttime += ampm;
}
// print the hour, minute and second:
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch % 60); // print the second
Serial.print("EST Time: ");
Serial.println(esttime);
}
// Setup MQTT subscription for onoff & slider feed.
ESP.wdtFeed();
MQTT_connect();
Serial.println("Signal Strength is " + String(WiFi.RSSI()));
Adafruit_MQTT_Subscribe *subscription;
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
if (digitalRead(14) == LOW) {
Serial.println("Door open");
if (activater == 1) {
Serial.println("Transmitting unlocked message");
String first = String("SIDE DOOR UNLOCKED!") + String(" EST Time is ") + esttime;
char message[50];
first.toCharArray(message, 50);
transmit = 1;
da_door.publish(message);
delay(2000);
}
else {
Serial.println("Door open, but not activated");
if (transmit == 1) {
da_door.publish("______________");
delay(2000);
transmit = 0;
}
}
}
if (digitalRead(14) == HIGH) {
Serial.println("Door closed");
if (transmit == 1) {
da_door.publish("______________");
delay(2000);
transmit = 0;
}
}
// ping the server to keep the mqtt connection alive
if(! mqtt.ping()) {
mqtt.disconnect();
}
ESP.wdtFeed();}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 5;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
char *readFromEEPROM(uint64_t sizevar) {
size_t i;
char *data = "";
for(i=0; i<=sizevar; i++)
{
data[i] = EEPROM.read(i);
}
return data;
}
void writeVarData() {
EEPROM.write(0, twelve);
EEPROM.write(1, twentyfour);
EEPROM.write(2, activater);
EEPROM.commit();
}
Make sure to change the placeholders in the code (they are green in the code above):
- your-wifi-username (change to your WiFi network's network name)
- your-wifi-password (change to your WiFi network's password)
- configuration-wifi-username (change to the WiFi network name you would like the door sensor to make (for configuration))
- configuration-wifi-password (change to the configuration WiFi password)
- your-Adafruit-username (change to your Adafruit username (found at accounts.adafruit.com))
- your-AIO-Key (change to your AIO key (obtained by going to one of your Adafruit IO dashboards and clicking on the yellow key button))
- your-activate-and-deactivate-page (change to the webpage you would like the activate/deactivate links on (the door sensor makes it))
- your-home-page (change to the webpage you would like the 12/24 hour time links on (the door sensor makes it))
- your-12-hour-page (change to the webpage that you would like to control 12-hour time (the door sensor makes it))
- your-24-hour-page (change to the webpage that you would like to control 24-hour time (the door sensor makes it))
- your-activater-page (change to the webpage that you would like to control activation (the door sensor makes it))
- your-deactivater-page (change to the webpage that you would like to control deactivation (the door sensor makes it))
How to mount:
Put reed switch on door frame and put magnet on door. Make sure reed switch conducts when a magnet is near it. Beware, the reed switch breaks easily if it's not insulated (the reed switch is glass).
Now you will get emails when anyone opens your door!
Put reed switch on door frame and put magnet on door. Make sure reed switch conducts when a magnet is near it. Beware, the reed switch breaks easily if it's not insulated (the reed switch is glass).
Now you will get emails when anyone opens your door!