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.
1) 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.
2) Required Hardware :
- Computer running Arduino software (version 1.8.7 or higher).
- ESP32 board.
- PIR sensor
- Jumper wires
- 1K Resistor
- 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 dev board 5V
- PIR GND to ESP32 GDN
- PIR DATA to ESP32 GPIO through a 1K Resistor (D2 in this tutorial).
Note: The ESP32 GPIOs require 3V3 signals (not 5V tolerent). For quick hack, you can only add a serial resistor of 1K between the PIR DATA pin and the ESP32 GPIO pin to protect the ESP32 GPIO from damage. However, for production, a 5V/3V3 level shifter is needed to guarantee long term circuit reliability. You can check this page to get a 5V/3V3 level shifter module.
3) 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”.
4) 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 = "publish/..../....."; // publish/username/apiKeyIn const char* mqtt_server = "mqtt.asksensors.com";
5) 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.
6) Source Code :
A basic source code is shown below. Please refer to the AskSensors Github page 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, 2020 * 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 = "publish/..../....."; // publish/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 = 2; 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); } } }
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.)
Hi “HACK IOT”,
Thank you for reaching out. To customize your binary graph, please follow these steps:
1- open your sensor device page and Go to the Modules Tab.
2- Click on the ‘Add graph’ button, choose ‘Binary’ as graph type.
3- Setup your binary graph by setting the On/OFF values and labels as shown in the picture https://blog.asksensors.com/wp-content/uploads/2019/12/image_pir.png , and click Save.
Kind Regards.