Security Sensor Tutorial Using PIR Sensor and ESP8266
This tutorial demonstrates how to create a security sensor, using a PIR sensor, ESP8266, and the Arduino IDE, to indicate both high and low movement.
Join the DZone community and get the full member experience.
Join For FreeThis tutorial will walk you through the steps of using an ESP8266 and a PIR Sensor (Passive Infrared Sensor) to detect motion and send you notifications using a Wia F
What You Will Need
- PIR Sensor (HC-SR501)
- ESP8266
- Female to Male Jumper Wires
- USB Cable
Before You Begin
If you haven't done so already, visit our tutorial on getting started with the ESP8266. It details the correct environment to complete this tutorial.
Connecting the Hardware
Connect your wires according to the chart:
| PIR Sensor | ESP8266 |
| :-------------: |:-------------:/| | GND | GND |
| OUT | D7 |
| VCC | 3.3V |
The PIR sensor runs on an operating voltage range — DC 4.5-20V. But, there is a way to power the sensor from a 3.3V source. The H
pin on the side of the sensor is denoted by VCC
in the illustration above and is connected to a voltage regulator that converts the 3.3V source.
Install Libraries
In the Arduino IDE, go to Sketch > Include Libraries > Manage Libraries
. Install each of the following libraries by searching for their name in the search bar within the modal. A button will appear in the bottom right of the box that will allow you to install the library.
- ArduinoJson
- ESP8266WiFi
- ArduinoHttpClient
Due to recent changes in the library, be sure to install ArduinoJson 6.0 so that you are up to date.
If a library doesn't show up in the results when you search it, you may need to update your Arduino IDE version. You can download the latest version here.
Code
In the Arduino IDE, copy and paste the following code:
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ArduinoHttpClient.h>
#include <Arduino.h>
const char* ssid = "wifi-ssid"; // Your WiFi ssid
const char* password = "wifi-password"; //Your Wifi password
/* Get this secret key from the wia dashboard, in the `configuration` tab
for your device. It should start with `d_sk` */
const char* device_secret_key = "your-device-secret-key";
// Wia API parameters
char server[] = "api.wia.io";
char path[] = "/v1/events";
char statePath[] = "/v1/devices/me";
int port = 80;
WiFiClient client;
int status = WL_IDLE_STATUS;
StaticJsonDocument<200> jsonBuffer;
HttpClient httpClient = HttpClient(client, server, port);
JsonObject& root = jsonBuffer.to<JsonObject>();
String response;
int statusCode = 0;
int BUTTON = 0;
int SENSOR = 13;
boolean buttonState = HIGH;
boolean buttonDown = false;
boolean stateAlarm = LOW;
long motion = LOW;
String dataStr = "";
String stateStr = "";
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(BUTTON, INPUT);
pinMode(SENSOR, INPUT);
digitalWrite(LED_BUILTIN, HIGH);
// initialize serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
WiFi.begin(ssid, password);
Serial.print("Attempting to connect to SSID: ");
Serial.print(ssid);
// attempt to connect to WiFi network:
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
// wait 5 seconds for connection:
delay(5000);
}
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Connected");
}
// Thing function runs continiously
void loop() {
buttonState = digitalRead(BUTTON);
if (buttonState == LOW && stateAlarm == LOW) {
if (buttonDown == false) {
buttonDown = true;
Serial.println("Alarm on!");
stateAlarm = HIGH;
digitalWrite(LED_BUILTIN, LOW);
updateStateWia(stateAlarm);
delay(750);
}
}
else if (buttonState == LOW && stateAlarm == HIGH) {
if (buttonDown == false) {
buttonDown = true;
stateAlarm = LOW;
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("Alarm off!");
updateStateWia(stateAlarm);
delay(750);
}
}
else {
buttonDown = false;
}
if (stateAlarm == HIGH) {
motion = digitalRead(SENSOR);
//Serial.println(String(motion));
if (motion == HIGH) {
Serial.println("Motion Detected!");
root["name"] = "motion";
root["data"] = String(motion);
sendToWia(root);
delay(2000);
}
}
}
void updateStateWia(boolean& state) {
if (state == HIGH) {
stateStr = "{\"state\": {\"enabled\": true}}";
}
else {
stateStr = "{\"state\": {\"enabled\": false}}";
}
Serial.println(stateStr);
httpClient.beginRequest();
httpClient.put(statePath);
httpClient.sendHeader("Content-Type", "application/json");
httpClient.sendHeader("Content-Length", stateStr.length());
httpClient.sendHeader("Authorization", "Bearer " + String(device_secret_key));
httpClient.beginBody();
httpClient.print(stateStr);
httpClient.endRequest();
}
// Adds the correct headers for HTTP and sends Data to Wia
void sendToWia(JsonObject& data) {
dataStr = "";
serializeJson(data, dataStr);
httpClient.beginRequest();
httpClient.post(path);
httpClient.sendHeader("Content-Type", "application/json");
httpClient.sendHeader("Content-Length", dataStr.length());
httpClient.sendHeader("Authorization", "Bearer " + String(device_secret_key));
httpClient.beginBody();
httpClient.print(dataStr);
httpClient.endRequest();
}
Replace the following values in the code by placing your own values in between the quotation marks.
your-WiFi-ssid
(This is the name of your WiFi network)your-WiFi-password
(Your WiFi network password)your-device-secret-key
(Navigate to the Wia Dashboard > Devices and choose your device. The device_secret_key will be in the Configuration tab)- If you do not have a Wia Account yet, sign up here
The code above publishes an Event to Wia every time it detects motion, with a name
value of motion
(you'll need this later on, when building your Flow) and a data
value equal to the reading from the motion sensor.
Make sure the correct board is selected. Go to tools > board
and select NodeMCU 1.0 (ESP-12E Module)
. Make sure the correct port is selected: tools > port
.
Turning on the Alarm
To turn on your alarm, press the flash button on the Esp 8266. The blue LED should turn on. To turn off the alarm, press and hold the flash button for at least 2 seconds, the blue LED will turn off.
Setting Up Your Flow
Create the Flow
Lets set up a flow that will send a notification to your phone when motion is detected by the PIR Motion Sensor.
Go to your Wia Dashboard and click Flows
in the left hand side menu. Create a new Flow with any name you like.
Add an Event Trigger Node
In Flow Studio, drag an Event
node from the Trigger section, and:
- Enter
motion
as the event name - Add your device
Add a State Logic Node
Now, add a Check State
node from the Logic section
- Enter
enabled
as the key - Select 'Equal to` from the Condition drop-down
- Enter
true
as the Value
Add a Notification Node
Next, drag over a Notification
node from the Action section.
- Enter "Motion Detected" as the Message.
Now, Wia can send you a message to the Wia mobile app when your Security Sensor detects a motion.
Add a Widget
Next, head over to your Device's 'Overview' tab. Click 'Add a Widget'. Give the Widget a name Motion Detected
, choose Widget type 'text', and enter the name of the Event i.e. motion
.
PIR Sensor Sensitivity Measures
The PIR Sensor allows you to change the delay time and the sensitivity level.
The PIR Sensor is a digital device. This means that it reads two values: HIGH and LOW. When the sensor detects movement, it reads HIGH. Otherwise, it reads LOW.
The delay setting determines how long the PIR Sensor will read HIGH after it has detected a motion. The sensitivity sensor determines the proximity at which the PIR Sensor will register a movement. This sensor is more accurate when it is set to a lower proximity level. You can control these settings using the orange panels located directly across from the pins you used to wire your device.
Trouble Shooting
If you are having trouble finding the correct board, refer back to our getting started with the ESP8266 tutorial.
If your port is not showing the USB option, try switching the USB cable and checking that the cable isn't "charge only." If this doesn't help, you may need to install a driver. This tutorial contains a section that will walk you through those steps.
If you are receiving the error StaticJsonDocument does not name a type,
its due to a breaking change introduced into the ArduinoJson
library. Go to sketch > include library
and manage libraries to update to version 6+.
Published at DZone with permission of Austin Spivey. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments