ESP8266 Projects

A silent alarm with Telegram and an ESP8266

Silent Alarm with Telegram and the ESP8266

In this project you create a motion detector that sends you a message when someone moves in front of it. In principle, this is a silent alarm– an alarm system that does not make any noise but discreetly tells you that something is in progress.

The sensor HC-SR501 is used here. You know this kind of sensors from the standard motion detectors that switch on the light as soon as someone passes by.

This is a so-called PIR sensor – PIR stands for Passive Infrared. This sensor therefore detects infrared radiation or heat radiated by bodies. In addition, it only turns on when this body is moving – otherwise it would eventually raise the alarm even when a warm heater is on.

This means that as soon as a person (or even a cat or dog) comes into the range of the motion detector, it registers the radiated heat and the movement and informs you.

Beginner

1 – 2 hours

ca. 10 $

For this project you need (quantities see description):

Prepare Telegram

First you need an account with Telegram – and the corresponding app for your smartphone or computer. In the following we use a smartphone. Telegram is free, ad-free, and works much like WhatsApp. However, here you have the possibility to create bots that you can interact with.

You can take advantage of that in this project by letting your ESP8266 “talk” to your Telegram bot. The bot in turn will immediately send you a notification.

In this tutorial on Pollux Labs you learn how to create your own Telegram bot.

Setting up the project

The set up on the breadboard is very quick: you just have to connect the motion sensor to your ESP8266:

You can see the labeling of the pins on the sensor when you lift off the white cap. Connect the sensor and your ESP8266 as follows

HC-SR501ESP8266
GNDGND
OUTD5
VCC3v3

And that was it with the hardware. Let’s have a look at the code.

The sketch for the motion detector

Now it is time for some code. If you have never used an ESP8266 with the Arduino IDE: In this tutorial you will learn how to make your ESP8266 available and program it in the Arduino IDE.

The required libraries

You need a total of three libraries. Two of them should already be pre-installed on your system: ESP8266WiFi.h and WiFiClientSecure.h – you need them to connect to your Wi-Fi network and send data.

The library UniversalTelegramBot.h handles the communication with your Telegram bot. You can find it in the Library Manager of the Arduino IDE – but it might be outdated. Therefore we recommend you to download the library here.

Then you need to include this library in your sketch by selecting Sketch > Include Library > Add .ZIP Library from the Arduino IDE Sketch menu and selecting the ZIP file you just downloaded.

Now copy the following sketch and load it onto your ESP8266

Note:Before your Telegram bot can receive messages, you must first open it and tap Start. You only have to do this once at the beginning.

View Sketch as .txt

/*
   Stiller Alarm mit Telegram - polluxlabs.net
*/

//Bibliotheken
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Deine WLAN-Zugangsdaten
const char* ssid = "NETZWERKNAME";
const char* password = "PASSWORT";

// Den Telegram-Bot initialisieren
#define botToken "DEIN TOKEN"  // den Bot-Token bekommst du vom Botfather)

//Deine User ID
#define userID "DEINE USERID"

WiFiClientSecure client;
UniversalTelegramBot bot(botToken, client);

const int sensor = 14; // Pin des Bewegungssensors, auf dem ESP Pin D5
bool motion = false;

// Indicates when motion is detected
void IRAM_ATTR detectingMovement() {
  motion = true;
}

//Verbindung zum WLAN
void connectToWiFi() {
  Serial.print("Verbinde mich mit: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

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

  // Verwendeter Pin
  pinMode(sensor, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(sensor), detectingMovement, RISING);
}

void loop() {

  if (motion == true) {
    connectToWiFi();
    bot.sendMessage(userID, "Hier bewegt sich etwas!", "");
    Serial.println("Bewegung erkannt");
    motion = false;
    WiFi.disconnect();
  }
}

The sketch step by step

Now let’s take a closer look at some important parts of the sketch for your motion detector.

First there are some data that you have to replace with your own: your Wi-Fi access data as well as your token and User ID from Telgram. Enter these data here:

const char* ssid = "DEIN WLAN-NETZWERK";
const char* password = "DEIN PASSWORT";
#define botToken "DEIN TOKEN"
#define userID "DEINE USER ID"

Then you create an instance of WiFiClientSecure names clientand also a botwith your botToken and client defined above.

WiFiClientSecure client;
UniversalTelegramBot bot(botToken, client);

Now a constant and a variable are needed. In the first one you define the pin to which the sensor is connected. Note: The numbers on ESP8266 and in the sketch are different. If you have connected the sensor to pin D5, this corresponds to 14 in the sketch.

Set the variable motion to false at the beginning of the sketch. This variable can have two states: false, if no motion is detected and true, if exactly that is the case. So you need the datatype bool, which can only take these two values.

const int sensor = 14; // Pin des Sensors, am ESP8266 Pin D5
bool motion = false; // Variable für eine erkannte Bewegung

The functions within the sketch

Now the first function comes into play. This callback function is called as soon as the sensor detects a movement and sends a 1(HIGH)to your ESP8266.

The function does nothing else but set the currently defined variable motion to true. This in turn sets the message to your Telegram bot in motion – which we will take a closer look at in a moment.

void IRAM_ATTR detectingMovement() {
  motion = true;
}

But first, there is another function in the sketch that connects your ESP8266 to the internet as soon as motion is detected.

void connectToWiFi() {
  Serial.print("Verbinde mich mit: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password); //hast du zu Beginn hinterlegt
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(300);
  }
  Serial.println("");
  Serial.println("Verbunden!");
}

The setup function

Again, there are a few basic things you need to do: Start the serial monitor, configure the client and set the pinMode for the connected sensor.

With the function attachInterrupt you define the motion detection. The first parameter contains the pin to which the sensor is connected. The second thing to do when something is detected: execute the function detectingMovement(). The third parameter defines when this should happen – when the signal at the pin changes from LOW to HIGH.


More detailed explanations of this function can be found in the Arduino reference.

void setup() {
  Serial.begin(115200);
  client.setInsecure();
  pinMode(sensor, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(sensor), detectingMovement, RISING);
}

The Loop

So here comes the crucial part of the sketch. The loop runs most of the time without executing anything. Only when the sensor sends a signal and the interrupt sets the variable motion to true, the condition in the if statement is fulfilled and something is started.


First the function connectToWiFi() is called and your ESP8266 connects to the Internet.

Send the message

Then it sends a message to your Telegram bot with bot.sendMessage().

This is the heart of your sketch, so to speak. The function sendMessage() takes three arguments:

  1. your User ID, which you entered in the sketch at the top.
  2. a message of your choice as String
  3. the parse mode – optional, we leave it empty in this project

So if your ESP8266 is connected to the internet, the message should appear on your smartphone after a few seconds.

Finally the variable motion is set to false again and the connection to the internet is cut.

void loop() {

  if (motion == true) {
    connectToWiFi();
    bot.sendMessage(userID, "Hier bewegt sich etwas!", "");
    Serial.println("Bewegung erkannt");
    motion = false;
    WiFi.disconnect();
  }
}

After that your project is back in its original state and waits for the next movement.
If you haven’t already done so, load the sketch onto your ESP8266 and try it out right away. And don’t forget: Before the first test you have to start your bot once by tapping start.

Adjustment of the sensor

On the bottom of the sensor you will find two potentiometers. If you turn the sensor upside down so that the board is facing up, you can adjust the sensitivity with the left potentiometer. Experiment with this to adjust the optimal range of the motion sensor.

At the right potentiometer you can adjust how long the sensor sends a HIGH signal before it is reset and can detect new movements. However, you will not use this function in this project because the sensor triggers an interrupt. How long the sensor sends the HIGH signal is not important here.

What’s next?

You now have a motion detector that you can use as a silent alarm that sends messages to your Telegram bot. In the second part of this project series you monitor the temperature: As soon as a value you have set is exceeded, you will receive a message on your smartphone.

On Pollux Labs we have many tutorials and projects, which deal with temperature and other sensors.

Have fun exploring! 🙂

Letzte Aktualisierung am 2020-11-26 / Affiliate Links / Bilder von der Amazon Product Advertising API

You may also like

Comments are closed.