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.
Project Overview
This tutorial shows how to get notifications in your Telegram account when the ESP8266 NodeMCU detects motion.
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.
Open Telegram and follow the next steps to create a Telegram Bot. First, search for “botfather” and click the BotFather as shown below. Or open this link t.me/botfather in your smartphone.
The following window should open and you’ll be prompted to click the start button.
Type /newbot and follow the instructions to create your bot. Give it a name and username.
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.
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” or open this link t.me/myidbot in your smartphone.
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.
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 Library created 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.
- Click here to download the Universal Arduino Telegram Bot library.
- Go to Sketch > Include Library > Add.ZIP Library...
- 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.
- Go to Sketch > Include Library > Manage Libraries.
- Search for “ArduinoJson”.
- Install the library.
We’re using ArduinoJson library version 6.5.12.
Parts Required
For this project, you need the following parts:
- ESP8266 (read Best ESP8266 development boards)
- Mini PIR Motion Sensor (AM312) or PIR motion sensor
- Breadboard
- Jumper wires
Schematic Diagram
For this project you need to wire a PIR motion sensor to your ESP8266 board. Follow the next schematic diagram.
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.
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/telegram-esp8266-nodemcu-motion-detection-arduino/
Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
*/
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Initialize Telegram BOT
#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // your Bot Token (Get from Botfather)
// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "XXXXXXXXXX"
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
const int motionSensor = 14; // PIR Motion Sensor
bool motionDetected = false;
// Indicates when motion is detected
void ICACHE_RAM_ATTR detectsMovement() {
//Serial.println("MOTION DETECTED!!!");
motionDetected = true;
}
void setup() {
Serial.begin(115200);
configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
// PIR Motion Sensor mode INPUT_PULLUP
pinMode(motionSensor, INPUT_PULLUP);
// Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
// Attempt to connect to Wifi network:
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;
}
}
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 BOTtoken variable.
#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // your Bot Token (Get from Botfather)
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; // PIR Motion Sensor
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.
// Indicates when motion is detected
void ICACHE_RAM_ATTR detectsMovement() {
//Serial.println("MOTION DETECTED!!!");
}
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):
// PIR Motion Sensor mode INPUT_PULLUP
pinMode(motionSensor, INPUT_PULLUP);
// Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
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.
At the same time, this is what you should get on the Serial Monitor.
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.
Nice!
The code was very good and simple. Good Job!
Can this code be adapted to send notifications every fifteen minutes of the thermistor reading connected to an ESP8266
Yes.
It’s possible.
Regards,
Sara
Have issues with Esp8266 Node Mcu compilation error . I ca upload a basic file but won’t uploaded this code. Reinstalled the drivers but nothing seems to help
Hi.
What is exactly the compilation error?
Regards,
Sara
Error compiling for board Node MCU 1.0 ( ESP-12E Module).
How to adjust the code if i am using water level sensor instead of pir motion sensor? Pls help me
Can i use Esp8288-01 module for this?
Yes, just make sure you use the right GPIO to support interrupts with ESP-01: https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/
That is a very awesome code for use Telegram with ESP8266, thank you Sarah and Rui !
I tested it now on an Wemos ESP8266, the serial monitor shows “Motion Detection!!” but i have no message in my Telegram “my_bot” after i put /start in it.
The bot code and chat id seems ok. What could be the problem ?
How can i troubleshoot this ?
Did you add all the details to the ESP8266 code? The Telegram Bot token and your Telegram user ID?
Hi Rui, finally a made a new bot , this time on: https://web.telegram.org , and there i could copy paste very easy the bot token. So the fault with me was the previous bot token. For me, there were no mistakes, but there was…
Perhaps you could put this info on one of your tutorials ?
Hi Sara,
Please help to advise how to go to my account to find my idbot. Thanks.
You’ll need to search IDbot and it should appear in the users found…
I use the Wemos D1 mini for this and works fine, thank you.
To use a fix ip-adress i used parts of a different code (who works), but on this code here, it don’t work. It is like the board reboots every time.
I added below “const char* password ” these lines:
IPAddress staticIP(192, 168, 1, 61);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns1(8, 8, 8, 8);
IPAddress dns2(8, 8, 4, 4);
below “WiFi.mode(WIFI_STA);” i add this line:
WiFi.config(staticIP, gateway, subnet);
What is wrong and how do i use a fix ip-adress with this code ?
i did everything step by step, i can read Motion dedected on serial monitor but i could not take a message from telegram? my library same as yours version i do not understand why? i could now worked it esp32 cam too, there is a message {“ok”:false,”error_code”:401,”description”:”[Error]: Unauthorized”}
Hi.
Double-check your botToken. It is a long string, so you may get it wrong somewhere.
Regards,
Sara
Hi Sara, Rui and fans of Randomnerdtutorials, make a new bot on: https://web.telegram.org , and there you can copy and paste in your sketch very easy the bot token and make no mistakes.
Hi.
That’s right!
Thanks for the tip.
Regards,
Sara
Hi, Just wonding if its possible to send a “call” to the telegram app on your phone?
Hi.
What do you mean?
Regards,
Sara
Well, Instead of sending a text it makes a phone call.
PIR has an HT7133 regulator. It needs 5V according to the datasheet. It can not be powered with 3,3V as you pointed in the diagram. I never made it work reliable with a 3,3V power supply. I assume this a mistake.
Hi.
We use this PIR motion sensor: https://makeradvisor.com/tools/mini-hc-sr505-pir-motion-sensor/
It woks with 3.3V.
Regards,
Sara
I’ve tested it with a HC-SR501 and a ESP8266 v3 powered by 5v from PC.
ESP (VIN) —> HC-SR501 (VCC)
ESP (D5/GPIO14) —> HC-SR501 (OUT)
ESP (GND) —> HC-SR501 (GND)
It worked fine with this setup.
hope it helps. 🙂
Got a question here about the PIR Sensor , I am using a LHI 878 Sensor, not sure what to apply to pins , ground is ok but the other are S (assuming source) and D for drain. Is source going to D5 andD to 3v? Been getting some odd responses, thanks
For the LHI 878 sensor i fount this datasheet:
https://media.digikey.com/pdf/Data%20Sheets/Excelitas%20PDFs/LHI_878_3901_April17,2019_Spec.pdf
There is a built in mosfet in source follower configuration. So D goes to positive, S should then be the output.
It is recommend to use a load resistor of 47Kohms i read at the datasheet.
Load is between S and ground.
Really good project! Do I understand correctly that another user will not be able to see messages from esp8266
Hi Alex.
Yes, that’s correct.
Only the user with the CHAT_ID you’ve inserted.
REgards,
Sara
then what if for all users?
What do you mean for all users?
You can simply remove the condition that checks the sender’s UID.
That way, it will listen to anyone who messages the bot.
Regards,
Sara
Sorry for being a pain, tried to load this project on a WeMos D1 R1and receive error compiling board WeMos D1R1 . I loaded a basic program Blink and it loads fine so have to believe it is not a board issue, possibly a compatibility issue, what are your this?Thanks
Sara , figured it out, it was an issue with the Arduino json file, had to downgrade to 5.13 and then it worked.
So , I have program loaded on Wemos D1 R1, paralled 2 – 100K ohm resistors because i do not have a 47K , 5V from Wemos to D Resistor in series with D5 and G to G on Wemos. Made a new bot and called it driveway, got a new Token, verified it was written properly and used the /start command in bot. What I now have is in chats , /start but no message, in serial window of IDE ……….. across the screen but nothing else . Checked baud rate and it is correct, any suggestions, finally got this far in the project and hate to abandon it now.
Hello
I’m trying to load the sketch … and I have the following error…..
‘class axTLS::WiFiClientSecure’ has no member named ‘setInsecure’
I don’t know how to fix the error….
Thanks for the help
So I have put this aside for some time now and decided to try it again, I get a boat load of error all related to the Arduinojson.h file. I at one time loaded an older version and got it to compile but now that don’t even work.
I think I used 5.13 or something similar.
Even then it would not see motion or scroll info on the serial monitor. If I crossed the sensor I think I jumped momentarily S and D it would show motion detected but never worked the way it was supposed to.
Using LHI 878 with 49K across S – D , Esp8266 lolin typical connections for G 3v and S to D5.
Hello and congratulations for your tutorials.
I am a beginner in these ESP’s I love electronics and these projects. I tested this code and it worked perfectly in my first ESP8266 NodeMCU 1.0 ESP-12E, instead of the pir sensor I just used a microswitch to put it in the mailbox and receive alerts when the postman inserts a letter. I would like to know if it would be possible in the message (Motion Detected) send the battery reading Volts too?
Hi.
Yes, you can do that.
You need to read the battery voltage using an analog pin.
Regards,
Sara
Dear Sara,
How to make the bot to notify if PIR or ESP goes offline? Someone who is making this as part of the simple security system would be interested to be notified about this
Thx
hi thanks for tutorial it works well my question is how can I add a light that turns on when the pir sensor acts at the same time it sends the message to the telegram (I am a learner)
tested and working ….now try to change from pir motion to irsensor
why can’t receive messages to telegram??
Hi.
Can you better describe your issue?
Regards,
Sara
Hi,
I have tested sucessfully on last month.
But today, I tested again and It didn’t work. Program not have bug, but Telegram Bot don’t message me.
Thank you.
Hi.
Update the library.
Our code is now compatible with the latest version of the library.
Regards,
Sara
HI, just to know, how do i write to change the line (CR).
Pex. Alarm !
Motion Detection
12/05/2021
I am having this error
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
I have tried to downgrade arduino json library but it did not avail.
Hi.
What’s the line of code highlighted with the error?
Or can you give more details about the error?
Regards,
Sara
Hi. I am very interested to know if you already have develop a program for nodemcu, mpu6050 and if the sensor detects a certain angle/acceleration it will notify user through Telegram. The one that I am trying to do is using IFTTT Maker but yours is much more easier to understand. I am very interested to know if it is possible to realize without the use of IFTTT Maker. Thank you very much & have a nice day ahead!
Hi.
Yes.
You try to combine the following tutorials:
– https://randomnerdtutorials.com/esp8266-nodemcu-mpu-6050-accelerometer-gyroscope-arduino/
– https://randomnerdtutorials.com/telegram-request-esp32-esp8266-nodemcu-sensor-readings/
I hope this helps.
Regards,
Sara
Thank you ☺️
Instead of manually asking for the reading through Telegram, is it possible for this method to receive the notification alert automatically?
Yes.
You can program your board to send a message to telegram every X number of seconds.
You can do that in the loop() of your program.
Regards,
Sara
When uploading a program it’s showing a error invalid head of packet can u the sollution
Hi.
You need to press the ESP32 BOOT button when you start seeing a lot of dots ……… on the debugging window.
This article might also help: https://randomnerdtutorials.com/solved-failed-to-connect-to-esp32-timed-out-waiting-for-packet-header/
Regards,
Sara
Hello Rui and Sara, very good this post as always just get the code and run, it works the first time.
My question is if there is any command that checks if it is connected, I caught a case that I couldn’t run the commands after 3 days, restarted and started working again.
I verified that you have a post to verify if it is connected to the wi-fi but I wanted something to verify if it is connected to the Telegram. I checked something on google and there is a command, but they use another library ( CTBot) and I found it interesting ” if (myBot.testConnection())
Serial.println(“nConnection Ok!”);
else
Serial.println(“nConnection failed!”);
I don’t know if the UniversalTelegramBot library would have something like that?
Hugs
Ricardo
Hi Sara, Thank you for your excellent work.
I don’t know English and I have translated this with Google !!! 🙁
I have implemented this process to a control sketh of the wooden boiler of my house, within a web-serves where I see the operation of it, from the sofa !!!.
The sketch you propose works perfectly for me in the ESP 32 WOORD 32s that I am using. When I implement communications with Telegram, an inconsistency occurs between the names of the objects that the libraries generate.
Originally both libraries use “client” as the name of the object, and the compiler gives an error …, and I have changed it to this:
WiFiClient client; // I establish the WiFi connector
WiFiServer server (80); // Set 80 webServer
WiFiClientSecure secured_client;
UniversalTelegramBot bot (BOTtoken, secured_client);
The bot.send function returns a “0” code.
bool resulta = bot.sendMessage (CHAT_ID, “Bot started up”, “”);
Serial.print (“Result start bot”);
Serial.println (result);
Alternatives?
Sorry but I have not said … And I do not receive any message on Telegram. : – ((
Hi.
what are exactly the errors that you’re getting?
Regards,
Sara
Hi Sara, Thank you for your interest. I am not an arduino expert ….
I enclose the twists of the program that I consider are important for the purpose and the copy of the messages that are displayed on the console.
You will see in the function “aviso_telegram” the call to the function ‘bot.sendMessage’ that I have seen returns a ‘bool’ and I show it in the console.
Specifically, it returns a ‘0’ without any other type of warning.
// Valores para el MySQL
#include <MySQL_Connection.h> // COnector con el MySQL
#include <MySQL_Cursor.h> // Puntero de insercion de filas en tabla del MySQL
IPAddress server_addr(192,168,0,104); // IP of the MySQL server here
char user[] = “arduino”; // MySQL user login username
char password[] = “xxxx”; // MySQL user login password
MySQL_Connection conn((Client *)&client); // Creacion del conector con MySQL
// QUIERY que enviamos al MySQL para insertar datos en la BD
…
// FUNCIONES
…
int debbuger = 0;
void trace(String posicion, int activo){ // debbug por consola
if (activo > 0) {
if (debbuger > 0){
Serial.println(posicion);
}
}
}
void aviso_telegram(int n){
// mensaje a telergram
// 1 temperatura en sala < 5 grados, posible congelacion equipos
// 2 sin sensores conectados
// 3 falta pelets
// 4 puesta abierta
//
trace(“Envio avisos por Telegram”,9);
bool resul = bot.sendMessage(CHAT_ID, “Bot started up”, “”);
Serial.print(“Resultado start bot “);
Serial.print(resul);
Serial.print(“Mensaje num. : “);
Serial.println(n);
switch (n){
case 1:
bot.sendMessage(CHAT_ID, “Texto 1”, “”);
break;
default:
bot.sendMessage(CHAT_ID, “No hay texto”, “”);
break;
}
}
…
WiFi.begin(ssid, clave);
#ifdef ESP32
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
#endif
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
….
void loop() {
if ((millis() – lastTime) > timerDelay) { // Hemos superado el tiempo de latencia para actualizr la MySQL
Serial.println(“Primera llamada a Telegram………………………..”);
aviso_telegram(9);
Serial.println(“Miro estado WiFi y reconecto en caso necesario”);
while (WiFi.status() != WL_CONNECTED) {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, clave);
delay(500);
}
….
18:39:30.802 -> Conectando a la WiFi: TP-Link_A7G4 …..
18:39:33.280 -> Conexion establecida con la IP : 192.168.0.202
18:39:33.313 -> Conectando con el Servidor MySQL, en la direccion IP : 192.168.0.104
18:39:33.313 -> …trying…
18:39:33.908 -> Connected to server version 8.0.27-0ubuntu0.20.04.1
18:39:34.569 -> Primera llamada a Telegram………………………..
18:39:42.533 -> Resultado start bot 0
18:39:42.533 -> Opcion mensaje envio Telegram : 9
18:39:50.532 -> Miro estado WiFi y reconecto en caso necesario
18:39:50.532 -> WiFi conectada.
18:39:50.532 -> Estado conexion con MySQL: 1
18:39:52.615 -> INSERT INTO arduino_db.datos_sensores (sen1, sen2, sen3, sen4, sen5, sen6, sen7, sen8, sen9, sen10) VALUES (-127.00, -127.00, 17.44, 23.00, 23.56, 16.00, -127.00, -127.00, 21.78, 45) —–> 184
18:39:53.244 -> Se actualiz la base de datos MySQL cada : 5 minutos.
18:40:01.212 -> Resultado start bot 0
18:40:01.212 -> Opcion mensaje envio Telegram : 4
18:40:09.670 -> Sensores conectados : 4
18:40:13.271 -> Sensores conectados : 4
18:40:16.905 -> Sensores conectados : 4
Hi Sara, Today I have been a bit busy and I could not get on with this until a while ago.
The process has been: From the sketch that you propose in this article, I have taken the loop and embedded it in my program (commenting on the rest of the instructions in my loop), the result ….. It does not work !!
I have been commenting instruction by instruction of my setup, and testing to see how it responded and I have located the specific instruction that makes it not work.
If I comment the instruction:
“WiFi.config (local_IP, gateway, subnet, primaryDNS, secondaryDNS);”
from my setup and I run, the messages come out correctly .!!! 🙂 🙂
I have it so that the ESP32 has a fixed IP and can access the web with the data from the sensors directly.
It would be good if someone tried to repeat this situation, in case it is a problem of updating libraries.
The only library that I have been able to see the version is
MySQlConnectorArduino V.1.1.1
If someone explains to me how to see the versions of the libraries, I could complete this information.
Anyway, thanks for your interest.
Hello, and thank you for the nice tutorial.
I have a question. If a person sends a message to the BOT, but the arduino is offline, is there any way to send a message “server is offline”?
Or since it has to be connected to the Wi-Fi, it won’t be able to send?
Hi.
Because it is offline, it won’t be able to send.
Regards
Sara
Hello, can i ask something ?
Can i use Wifi Shield for this project ?
Is there any code that need to changes ?
Thank you for very interesting projects. I was wondering if you can incorporate the ESP.deepSleep() function in the code.
Hi.
Yes. If you use the PIR motion sensor as an external wake up source.
Regards,
Sara
Do I really need to buy the Hardware components for the project to function?
Hi.
To detect motion you need a motion sensor.
If you just want to send messages to telegram, you can omit the sensor section.
Regards,
Sara
Hi Rui and Sara, how can I solve this problem?
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiMulti.cpp: In function ‘wl_status_t waitWiFiConnect(uint32_t)’:
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiMulti.cpp:89:5: error: ‘esp_delay’ was not declared in this scope
89 | esp_delay(connectTimeoutMs,
| ^~~~~~~~~
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiMulti.cpp: In member function ‘int8_t ESP8266WiFiMulti::startScan()’:
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiMulti.cpp:241:5: error: ‘esp_delay’ was not declared in this scope
241 | esp_delay(WIFI_SCAN_TIMEOUT_MS,
| ^~~~~~~~~
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiSTA-WPS.cpp: In member function ‘bool ESP8266WiFiSTAClass::beginWPSConfig()’:
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiSTA-WPS.cpp:77:5: error: ‘esp_suspend’ was not declared in this scope
77 | esp_suspend( { return _wps_config_pending; });
| ^~~~~~~~~~~
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiGeneric.cpp: In member function ‘bool ESP8266WiFiGenericClass::mode(WiFiMode_t)’:
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiGeneric.cpp:442:9: error: ‘esp_delay’ was not declared in this scope
442 | esp_delay(timeoutValue, m { return wifi_get_opmode() != m; }, 5);
| ^~~~~~~~~
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiGeneric.cpp: In member function ‘int ESP8266WiFiGenericClass::hostByName(const char*, IPAddress&, uint32_t)’:
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiGeneric.cpp:626:9: error: ‘esp_delay’ was not declared in this scope
626 | esp_delay(timeout_ms, { return _dns_lookup_pending; }, 1);
| ^~~~~~~~~
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiScan.cpp: In member function ‘int8_t ESP8266WiFiScanClass::scanNetworks(bool, bool, uint8, uint8*)’:
C:\Users\giasc\Documents\Arduino\libraries\ESP8266WiFi\src\ESP8266WiFiScan.cpp:100:9: error: ‘esp_suspend’ was not declared in this scope
100 | esp_suspend( { return !ESP8266WiFiScanClass::_scanComplete && ESP8266WiFiScanClass::_scanStarted; });
| ^~~~~~~~~~~
exit status 1
Errore durante la compilazione per la scheda LOLIN(WEMOS) D1 R2 & mini.
Hi.
check your ESP8266 boards version.
You may need to downgrade in Tools > Boards > Boards Manager > ESP8266.
Regards,
Sara
Dear Sara Santos,
Is it possible to “enable and disable” the “bot and the motion detection” via sending telegram massages? Can anyone revise the code and help me (I am not able to do it)
Best Regards,
Kemal
Hi this is really good project
I just want to know can I add multiple user id 3 or 4 user to send them the same message.
I already try to do it, but I have to define every user alone, is there is an away to put them all together in one define?
Hi.
You can create a Telegram group and all people in the group will receive the messages-
We have an example tutorial with a Telegram group. You can use the relevant parts in this project: https://randomnerdtutorials.com/telegram-group-esp32-esp8266/
I hope this helps.
Regards,
Sara
Thank you for your reply
Yes, it helps me very good it achieves my requirements.
Hi Sara!
Congrats! Your and Raul’s jobs is great.
I’m doing a project and I’d like to implement Telegram messages but I’m receiving the error below:
conflicting declaration ‘WiFiClient client’
Notice that in my code I have the eclarations bellow:
WiFiClientSecure client; // for Telegram
WiFiClient client; // fpr WiFi
Could you help me?
Thanks a lot and tell me if I need to send more details.
Alberto Branquinho
Hi.
You have two different variables with the same name “client”.
Your second wifi client needs another name.
For example:
WiFiClient client2;
Regards,
Sara
‘X509List’ does not name a type; did you mean ‘xList’?
Could you please help me solve this?
Hello,
thank you for this nice tutorial. Is it possible to use a WEMOS D1 mini instead of a NodeMCU (ESP32)?
Best regards
Jens
Yes.
This tutorial is compatible with ESP8266 boards.
Regards,
Sara
How in the event of the loss of one wifi ap automatically switches to a another backup wifi ap ?
Hi.
This can be a great help: https://randomnerdtutorials.com/esp32-wifimulti/
Regards,
Sara
I have searched and there seems to be a way where you can enter the bot token and chat id from a server page just like wifi. I cannot find this sketch and have been trying to get it to work. It seems pointers are the way to go regarding this ?. But still no luck. All I want is to be able to send my project to somebody and have them enter their credentials. The only other option is I have to do it and I don’t want to know others bot token or chat id. I have 4 sketches 99% done but can’t get past this
Perhaps this is your looking for:
What ?, nothing is showing.
Had problem to reply to myself 🙂
So… it was this: web.telegram.org/k/#-708148908
It ‘s so easy to copy the the bot token and chat id and to paste it somewhere else.
thank for the guide .so helpful for me ?
it work on esp8266
-but i used for ultrasonic sonic hc-sr04
Instead of IR sensor, I use HLK2410 radar sensor module.
Works very well.
Thank you for the code.