Connect PIR Motion Sensor and ESP32 to AskSensors over MQTT

PIR sensors allow to detect motion based on the detection of infrared energy emitted by a moving body, it means that we can use it to know when someone enters and leaves a certain area.

This tutorial shows how to detect motion with AskSensors IoT platform using the ESP32 and PIR sensor.  PIR motion detection is widely used to turn on the lights, trigger an alarm or many other applications.

a) Prerequisites :
· Active AskSensors account: Create AskSensors account.
· Create a new sensor. Follow the simple process described here.
· Follow these steps to get familiar with AskSensors.

b) Required Hardwares :
· Computer running Arduino software (version 1.8.7 or higher).
· ESP32 board.
. PIR sensor
. Jumper wires
. Breadboard
· Micro USB cable.

The connection diagram of this PIR sensor to the ESP32 is quite simple. Three pins need to be connected:

. PIR VCC to ESP32 5V
. PIR GND to ESP32 GDN
. PIR DATA to ESP32 GPIO (D2 in this tutorial).

connection diagram PIR sensor ESP32 MQTT

c) Install ESP32 in Arduino IDE:
If you haven’t already installed the ESP32 board in your Arduino IDE, follow these next instructions:
· Install the latest version of the Arduino IDE software (1.8.7 or higher).
· In your Arduino IDE, go to File> Preferences.
· Go to the “Additional Board Manager URLs” field, Enter the following URL: https://dl.espressif.com/dl/package_esp32_index.json

If you already have the ESP8266 boards URL, separate the URLs with a comma as shown below:
https://dl.espressif.com/dl/package_esp32_index.json,http://arduino.esp8266.com/stable/package_esp8266com_index.json

Now, open boards manager (Tools > Board > Boards Manager), search for ESP32 and click the install button for the “ESP32 by Espressif Systems”.

d) Software :
· Install the MQTT PubSubClient Library for the Arduino IDE if you haven’t already.
. Download this demo from the AskSensors Github page.

The provided code simply reads the status of the PIR sensor and send this information to AskSensors over MQTT. You need to modify the following variables:
· Your network credentials, so that ESP8266 can establish a connection with existing network
· The Api Key In and username to set the MQTT Topic:username/apiKeyIn

const char* ssid = “…..”; // Wifi SSID
const char* password = “…..”;// Wifi Password
const char* username = “……………..”; // my AskSensors username
const char* pubTopic = “……./…..”; // username/apiKeyIn
const char* mqtt_server = “mqtt.asksensors.com”;

e) Flash the code to your ESP32
· Connect your ESP32 board to the computer via serial/USB and upload the code using the Arduino IDE.
· Check your Sensor data stream on AskSensors.
· You can cross-check the AskSensors graph readings with the values being printed on your ESP32 Serial Terminal.
. You can customize a Binary graph to plot your data as showing by next pictures.

pir esp32 mqtt no motion

pir esp32 mqtt motion detected

f) Source Code :
A basic source code is shown below. Please refer to the AskSensors Github page(https://github.com/asksensors/AskSensors-ESP32-PIR) to get the latest version and updates.

/*

* MQTT and AskSensors IoT Platform

* Description: ESP32 publishes PIR motion data to AskSensors over MQTT

*  Author: https://asksensors.com, 2019

*  github: https://github.com/asksensors

*/

#include <WiFi.h>

#include <PubSubClient.h>

 

//TODO: ESP32 MQTT user config

const char* ssid = “………………”; // Wifi SSID

const char* password = “………………”; // Wifi Password

const char* username = “……………..”; // my AskSensors username

const char* pubTopic = “………………/………………”; // username/apiKeyIn

const unsigned int writeInterval = 25000;   // write interval (in ms)

//AskSensors MQTT config

const char* mqtt_server = “mqtt.asksensors.com”;

unsigned int mqtt_port = 1883;

int PIR_data = 22;

WiFiClient askClient;

PubSubClient client(askClient);

 

void setup() {

Serial.begin(115200);

Serial.println(“*****************************************************”);

Serial.println(“********** Program Start : ESP32 publishes PIR Motion data to AskSensors over MQTT”);

Serial.print(“********** connecting to WIFI : “);

Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(“.”);

}

Serial.println(“”);

Serial.println(“->WiFi connected”);

Serial.println(“->IP address: “);

Serial.println(WiFi.localIP());

client.setServer(mqtt_server, mqtt_port);

client.setCallback(callback);

pinMode(PIR_data,INPUT); // pir data as input

}

void loop() {

if (!client.connected())

reconnect();

client.loop();

bool PIR_status = digitalRead(PIR_data);

if(PIR_status){

Serial.println(“PIR motion detected”);

} else {

Serial.println(“NO PIR motion detected”);

}

Serial.println(“********** Publish MQTT data to ASKSENSORS”);

char mqtt_payload[30] = “”;

snprintf (mqtt_payload, 30, “m1=%ld”, PIR_status);

Serial.print(“Publish message: “);

Serial.println(mqtt_payload);

client.publish(pubTopic, mqtt_payload);

Serial.println(“> MQTT data published”);

Serial.println(“********** End “);

Serial.println(“*****************************************************”)

delay(writeInterval);// delay

}

void callback(char* topic, byte* payload, unsigned int length) {

Serial.print(“Message arrived [“);

Serial.print(topic);

Serial.print(“] “);

for (int i = 0; i < length; i++) {

Serial.print((char)payload[i]);

}

Serial.println();

}

void reconnect() {

// Loop until we’re reconnected

while (!client.connected()) {

Serial.print(“********** Attempting MQTT connection…”);

// Attempt to connect

if (client.connect(“ESP32Client”, username, “”)) {

Serial.println(“-> MQTT client connected”);

} else {

Serial.print(“failed, rc=”);

Serial.print(client.state());

Serial.println(“-> try again in 5 seconds”);

// Wait 5 seconds before retrying

delay(5000);

}

}

}

Tags:

2 Comments
  1. Hello,
    Thank you for sharing this article.
    Can You show how to setup a graph as described in this phrase (You can customize a Binary graph to plot your data as showing by next pictures.)

Leave a reply