https://randomnerdtutorials.com/telegram-esp8266-nodemcu-motion-detection-arduino/

This tutorial shows how to send notifications to your Telegram account when the ESP826 NodeMCU detects motion. As long as you have access to the internet in your smartphone, you’ll be notified no matter where you are. The ESP board will be programmed using Arduino IDE.

ESP8266 NodeMCU PIR Motion Sensor Telegram Send Message Notification Arduinohttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Telegram-Send-Message-Notification-Arduino.jpg?resize=300%2C169&ssl=1 300w, https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Telegram-Send-Message-Notification-Arduino.jpg?resize=1024%2C576&ssl=1 1024w, https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Telegram-Send-Message-Notification-Arduino.jpg?resize=768%2C432&ssl=1 768w" sizes="(max-width: 840px) 100vw, 840px" data-recalc-dims="1" data-reader-unique-id="4" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 786.09375px; margin-inline-start: -70px;">

Project Overview

This tutorial shows how to get notifications in your Telegram account when the ESP8266 NodeMCU detects motion. 

ESP8266 NodeMCU with PIR Motion Sensor Send Message Notification to Telegram using Arduino IDEhttps://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Send-Message-Notificatio-Telegram.png?resize=300%2C135&ssl=1 300w, https://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Send-Message-Notificatio-Telegram.png?resize=768%2C346&ssl=1 768w" sizes="(max-width: 840px) 100vw, 840px" data-recalc-dims="1" data-reader-unique-id="9" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 786.09375px; margin-inline-start: -70px;">

Here’s an overview on how the project works:

  • You’ll create a Telegram bot for your ESP8266.
  • The ESP8266 is connected to a PIR motion sensor.
  • When the sensor detects motion, the ESP8266 sends a warning message to your telegram account.
  • You’ll be notified in your telegram account whenever motion is detected.

This is a simple project, but shows how you can use Telegram in your IoT and Home Automation projects. The idea is to apply the concepts learned in your own projects.

Introducing Telegram

Telegram Messenger is a cloud-based instant messaging and voice over IP service. You can easily install it in your smartphone (Android and iPhone) or computer (PC, Mac and Linux). It is free and without any ads. Telegram allows you to create bots that you can interact with.

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram Bot API“.

The ESP8266 will interact with the Telegram bot to send messages to your telegram account. Whenever motion is detected, you’ll receive a notification in your smartphone (as long as you have access to the internet).

Creating a Telegram Bot

Go to Google Play or App Store, download and install Telegram.

Install and Download Telegramhttps://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Install-Telegram.png?resize=300%2C228&ssl=1 300w" sizes="(max-width: 354px) 100vw, 354px" data-recalc-dims="1" data-reader-unique-id="36" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

Open Telegram and follow the next steps to create a Telegram Bot. First, search for “botfather” and click the BotFather as shown below.

botfatherhttps://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Telegram-Botfather.png?resize=300%2C164&ssl=1 300w" sizes="(max-width: 362px) 100vw, 362px" data-recalc-dims="1" data-reader-unique-id="41" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

The following window should open and you’ll be prompted to click the startbutton.

Telegram Start BotFather to Create a new Bothttps://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/start-bot-father-telegram.png?resize=149%2C300&ssl=1 149w" sizes="(max-width: 352px) 100vw, 352px" data-recalc-dims="1" data-reader-unique-id="54" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

Type /newbot and follow the instructions to create your bot. Give it a name and username.

Telegram BotFather Create a New Bothttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Create-bot-Telegram-Botfather_f.png?resize=268%2C300&ssl=1 268w" sizes="(max-width: 354px) 100vw, 354px" data-recalc-dims="1" data-reader-unique-id="59" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

If your bot is successfully created, you’ll receive a message with a link to access the bot and the bot token. Save the bot token because you’ll need it so that the ESP8266 can interact with the bot.

Telegram BotFather Get Bot Tokenhttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Bot-Token-Telegram-Bot-Father.png?resize=199%2C300&ssl=1 199w" sizes="(max-width: 356px) 100vw, 356px" data-recalc-dims="1" data-reader-unique-id="66" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

Get Your Telegram User ID

Anyone that knows your bot username can interact with it. To make sure that we ignore messages that are not from our Telegram account (or any authorized users), you can get your Telegram User ID. Then, when your telegram bot receives a message, the ESP can check whether the sender ID corresponds to your User ID and handle the message or ignore it.

In your Telegram account, search for “IDBot

Telegram Get Chat ID with IDBothttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Telegram-ID-Bot.png?resize=300%2C149&ssl=1 300w" sizes="(max-width: 348px) 100vw, 348px" data-recalc-dims="1" data-reader-unique-id="75" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

Start a conversation with that bot and type /getid. You will get a reply back with your user ID. Save that user ID, because you’ll need it later in this tutorial.

Telegram Get Chat ID with IDBot getidhttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Telegram-Get-Chat-ID.png?resize=212%2C300&ssl=1 212w" sizes="(max-width: 354px) 100vw, 354px" data-recalc-dims="1" data-reader-unique-id="81" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

Preparing Arduino IDE

We’ll program the ESP8266 board using Arduino IDE, so make sure you have them installed in your Arduino IDE.

Universal Telegram Bot Library

To interact with the Telegram bot, we’ll use the Universal Telegram Bot Librarycreated by Brian Lough that provides an easy interface for the Telegram Bot API.

Follow the next steps to install the latest release of the library.

  1. Click here to download the Universal Arduino Telegram Bot library.
  2. Go to Sketch Include Library > Manage Libraries.
  3. Add the library you’ve just downloaded.

Important: don’t install the library through the Arduino Library Manager because it might install a deprecated version.

For all the details about the library, take a look at the Universal Arduino Telegram Bot Library GitHub page.

ArduinoJson Library

You also have to install the ArduinoJson library. Follow the next steps to install the library.

  1. Go to Skech Include Library > Manage Libraries.
  2. Search for “ArduinoJson”.
  3. Install the library.

We’re using ArduinoJson library version 6.5.12.

Install in Arduino IDE the ArduinoJSON libraryhttps://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Install-ArduinoJson-Library.png?resize=300%2C169&ssl=1 300w, https://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Install-ArduinoJson-Library.png?resize=768%2C433&ssl=1 768w" sizes="(max-width: 786px) 100vw, 786px" data-recalc-dims="1" data-reader-unique-id="119" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 786px; margin-inline-start: -69.953125px;">

Parts Required

For this project, you need the following parts:

Schematic Diagram

For this project you need to wire a PIR motion sensor to your ESP8266 board. Follow the next schematic diagram.

ESP8266 NodeMCU PIR Motion Sensor Wiring Diagramhttps://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Wiring-Diagram.png?resize=300%2C151&ssl=1 300w, https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Wiring-Diagram.png?resize=1024%2C515&ssl=1 1024w, https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/07/ESP8266-NodeMCU-PIR-Motion-Sensor-Wiring-Diagram.png?resize=768%2C387&ssl=1 768w" sizes="(max-width: 840px) 100vw, 840px" data-recalc-dims="1" data-reader-unique-id="139" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 786.09375px; margin-inline-start: -70px;">

In this example, we’re wiring the PIR motion sensor data pin to GPIO 14. You can use any other suitable GPIO. Read ESP8266 GPIO Guide.

Telegram Motion Detection with Notifications – ESP8266 Sketch

The following code uses your Telegram bot to send a warning message to your telegram account whenever motion is detected. To make this sketch work for you, you need to insert your network credentials (SSID and password), the Telegram Bot token and your Telegram user ID.



#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>


const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";


#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  




#define CHAT_ID "XXXXXXXXXX"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

const int motionSensor = 14; 
bool motionDetected = false;


void ICACHE_RAM_ATTR detectsMovement() {
  
  motionDetected = true;
}

void setup() {
  Serial.begin(115200);
  client.setInsecure();

  
  pinMode(motionSensor, INPUT_PULLUP);
  
  attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);

  
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  bot.sendMessage(CHAT_ID, "Bot started up", "");
}

void loop() {
  if(motionDetected){
    bot.sendMessage(CHAT_ID, "Motion detected!!", "");
    Serial.println("Motion Detected");
    motionDetected = false;
  }
}

View raw code

How the Code Works

This sections explain how the code works. Continue reading or skip to the Demonstration section. 

Start by importing the required libraries.

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

Network Credentials

Insert your network credentials in the following variables.

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Telegram Bot Token

Insert your Telegram Bot token you’ve got from Botfather on the BOTtokenvariable.

#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  

Telegram User ID

Insert your chat ID. The one you’ve got from the IDBot.

#define CHAT_ID "XXXXXXXXXX"

Create a new WiFi client with WiFiClientSecure.

WiFiClientSecure client;

Create a bot with the token and client defined earlier.

UniversalTelegramBot bot(BOTtoken, client);

Motion Sensor

Define the GPIO that the motion sensor is connected to.

const int motionSensor = 14; 

The motionDetected boolean variable is used to indicate whether motion was detected or not. It is set to false by default.

bool motionDetected = false;

detectsMovement()

The detectsmovement() function is a callback function that will be executed when motion is detected. In this case, it simply changes the state of the motionDetected variable to true.


void ICACHE_RAM_ATTR detectsMovement() {
  
}

setup()

In the setup(), initialize the Serial Monitor.

Serial.begin(115200);

For the ESP8266, you need to use the following line:

client.setInsecure();

In the library examples for the ESP8266 they say: “This is the simplest way of getting this working. If you are passing sensitive information, or controlling something important, please either use certStore or at least client.setFingerPrint“.

PIR Motion Sensor Interrupt

Set the PIR motion sensor as an interrupt and set the detectsMovement() as the callback function (when motion is detected, that function will be executed):


pinMode(motionSensor, INPUT_PULLUP);

attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);

Note: Recommended reading: ESP8266 with PIR Motion Sensor using Interrupts and Timers

Init Wi-Fi

Initialize Wi-Fi and connect the ESP8266 to your local network with the SSID and password defined earlier.

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.println("Connecting to WiFi..");
}

Finally, send a message to indicate that the Bot has started up:

bot.sendMessage(CHAT_ID, "Bot started up", "");

loop()

In the loop(), check the state of the motionDetected variable. 

void loop() {
  if(motionDetected){

If it’s true, it means that motion was detected. So, send a message to your Telegram account indicating that motion was detected. 

bot.sendMessage(CHAT_ID, "Motion detected!!", "");

Sending a message to the bot is very simply. You just need to use the sendMessage() method on the bot object and pass as arguments the recipient’s chat ID, the message, and the parse mode.

bool sendMessage(String chat_id, String text, String parse_mode = "")

Finally, after sending the message, set the motionDetected variable to false, so it can detect motion again. 

motionDetected = false;

That’s pretty much how the code works.

Demonstration

Important: go to your Telegram account and search for your bot. You need to click “start” on a bot before it can message you.

Upload the code to your ESP8266 board. Don’t forget to go to Tools Board and select the board you’re using. Go to Tools Port and select the COM port your board is connected to.

After uploading the code, press the ESP8266 on-board RST button so that it starts running the code. Then, you can open the Serial Monitor to check what’s happening in the background.

When your board first boots, it will send a message to your Telegram account: “Bot started up”. Then, move your hand in front of the PIR motion sensor and check that you’ve received the motion detected notification.

ESP32 ESP8266 Motion Detected Telegram Notificationhttps://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/Motion-Detected-Telegram-Notification.png?resize=300%2C238&ssl=1 300w" sizes="(max-width: 352px) 100vw, 352px" data-recalc-dims="1" data-reader-unique-id="586" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

At the same time, this is what you should get on the Serial Monitor.

ESP32 ESP8266 Telegram Motion Detected Serial Monitor Demonstrationhttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/06/ESP32-Telegram-Motion-Detected-Serial-Monitor-Demonstration.png?resize=300%2C195&ssl=1 300w" sizes="(max-width: 669px) 100vw, 669px" data-recalc-dims="1" data-reader-unique-id="590" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 669px; margin-inline-start: -11.453125px;">

Wrapping Up

In this tutorial you’ve learned how to create a Telegram Bot to interact with the ESP8266 NodeMCU board. When motion is detected, a message is sent.

With this bot, you can also use your Telegram account to send messages to the ESP8266 to control its outputs or request sensor readings, for example.

The great thing about using Telegram to control your ESP boards, is that as long as you have an internet connection (and your boards too), you can control and monitor them from anywhere in the world.

More projects with Telegram:

We hope you’ve found this project interesting. Learn more about the ESP8266 with our resources:

Thanks for reading.

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »