February 4th, 2019 by cedcraftscodes
Today, we will learn how to send a Facebook Chat when our PIR sensor detects motion. This tutorial is helpful if you want to create a security system which alerts you when someone is entering your house. You can also include this project in one of your home automation system.
PIR Sensor
NodeMcu ESP12 Lolin V3
Jumper Wires
Led Light
220Ohm Resistor
Facebook Page
Facebook Developer Account
If you already set up your NodeMcu Board, skip this section.
We need to add esp8266 to our Arduino IDE. Open up your IDE then go to “File -> Preferences” or simply hit “Ctrl + comma”
Paste http://arduino.esp8266.com/stable/package_esp8266com_index.json in additional board manager URLs.
Go to “Tools -> Board -> Boards Manager” search and install esp8266
Close and restart your Arduino IDE
Plugin your NodeMcu to your computer.
Go to Tools -> Port and select the COM Port of your NodeMCU. If you are not sure what port your NodeMcu is plugged in, go to Device Manager -> Ports (COM & LPT)
Now select NodeMcu 1.0 (ESP-12E Module) by clicking Tools -> Board. Scroll down until you find it.
To test the connection, upload this code to your NodeMcu Lolin V3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | int pirPin = 13; int ledPin = 12; int state = LOW; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); pinMode(pirPin, INPUT); } void loop(){ if (digitalRead(pirPin) == HIGH) { digitalWrite(ledPin, HIGH); if (state == LOW) { Serial.println("Motion detected"); state = HIGH; } } else { digitalWrite(ledPin, LOW); if (state == HIGH){ state = LOW; } } } |
The LED should light up when motion is detected. If it doesn’t light up, consider adjusting the delay and sensitivity knob. Note that the code above is only for testing the connection.
You need to install XAMPP. You can download XAMPP here. We will put our PHP codes to XAMPP htdocs folder. After installing, Open XAMPP Control Panel and start up Apache
We need to expose our local web server so we can add it later on Facebook as a webhook. If you do not have NgRok, you can download it on their website. Register an account. Follow this tutorial on how to start an HTTP tunnel on port 80
You can also host the PHP files on your own web server but make sure it has an SSL certificate.
First, we need to create a Facebook Page for our Facebook Chat App. After creating a Facebook Page, Go to Facebook Developers.
Create a Facebook app. In the sidebar, add a product and select Messenger.
Select your page and Copy the Page Access Token. We will need it in our PHP Scripts.
Copy the URL in your NgRok and add /senderId.php (Depends on where you put the PHP Scripts). Tick the message checkbox.
Take note of Callback URL and Verify Token. When you are done, click Verify and Save. (If verification doesn’t work, make sure you are using HTTPS and the PHP code is deployed already). If you have not deployed your code yet and doesn’t know how to get your sender id, follow the “Getting your SenderId” section below.
We need to know what our sender id is. We need to do this step in order to specify where the message will go. Change the hubVerifyToken and accessToken.
Save the file as senderId.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php $hubVerifyToken = 'yourverifytoken'; $accessToken = "youraccesstoken"; if (isset($_REQUEST['hub_verify_token']) && $_REQUEST['hub_verify_token'] === $hubVerifyToken) { echo $_REQUEST['hub_challenge']; exit; } $input = json_decode(file_get_contents('php://input'), true); $senderId = $input['entry'][0]['messaging'][0]['sender']['id']; $response = null; $answer = "Your sender id is ".$senderId; $response = [ 'recipient' => [ 'id' => $senderId ], 'message' => [ 'text' => $answer ] ]; $ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.$accessToken); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); if(!empty($input)){ $result = curl_exec($ch); } curl_close($ch); ?> |
Go back to Facebook Developer and point the webhook URL to your senderId.php file
Send a message to your Facebook Page. You should be able to see a message containing “Your sender id is (NUMBERS)”
We will change the code a little bit. Notice that the code is somewhat the same. We only need to change the verify and access token, as well as the sender id. Save the file as bot.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php date_default_timezone_set('Asia/Manila'); $hubVerifyToken = 'yourverifytoken'; $accessToken = "youraccesstokenEAAPjJXpt8DIBAMXnJli......"; if (isset($_REQUEST['hub_verify_token']) && $_REQUEST['hub_verify_token'] === $hubVerifyToken) { echo $_REQUEST['hub_challenge']; exit; } $answer = "Motion Detected! ".date("Y-m-d H:i:s"); $response = [ 'recipient' => [ 'id' => '2299615480051264' ], 'message' => [ 'text' => $answer ] ]; $ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.$accessToken); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_exec($ch); curl_close($ch); ?> |
Go back to Facebook Developer and point your webhook to bot.php.Â
The code above will send a message to our Facebook Account when triggered by our NodeMCU. Our NodeMcu module will send an HTTP Post request to our webhook URL.
Visit your URL and click the lock button beside it. Click Certificates. A window will pop up. Click Details and scroll down until you find the thumbprint.
Copy the Thumbprint
Before uploading the code to our NodeMcu ESP 12, we need to change first the SSID or your Wifi Name and wifi password. You also need to change this line of code.
http.begin(“https://fbd3a163.ngrok.io/pirmotionfb/bot.php”, “yourcertificatethumbprint”);
The first parameter is your webhook URL and the second one is your certificate thumbprint.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #include <ESP8266HTTPClient.h> #include <ESP8266WiFi.h> int pirPin = 13; int ledPin = 12; int state = LOW; const char *ssid = "yourwifissid"; const char *password = "yourwifipassword"; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); pinMode(pirPin, INPUT); delay(1000); Serial.begin(9600); WiFi.mode(WIFI_OFF); delay(1000); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println(""); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void loop(){ if (digitalRead(pirPin) == HIGH) { digitalWrite(ledPin, HIGH); if (state == LOW) { Serial.println("Motion detected"); if(WiFi.status() == WL_CONNECTED) { HTTPClient http; String postData = "action=showStat"; http.begin("https://fbd3a163.ngrok.io/pirmotionfb/bot.php", "4571789e29a8368fd8f8433e28c456e8116369d8"); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); int httpCode = http.POST(postData); String payload = http.getString(); } state = HIGH; } } else { digitalWrite(ledPin, LOW); if (state == HIGH){ state = LOW; } } } |
After uploading the code, test it out! You should be able to receive a message from your Facebook Page including the date and time when the motion is detected.
That’s it! Hope it works. If you need assistance, feel free to comment down below.
Please like and share this tutorial by clicking the share button below.
Comments