This tutorial shows how to send notifications to your Telegram account when the ESP32 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 ESP32 detects motion.
Here’s an overview on how the project works:
- You’ll create a Telegram bot for your ESP32.
- The ESP32 is connected to a PIR motion sensor.
- When the sensor detects motion, the ESP32 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 ESP32 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 ESP32 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 ESP32 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 Skech > 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:
- ESP32 board (read Best ESP32 dev boards)
- Mini PIR motion sensor (AM312) or PIR motion sensor (HC-SR501)
- Jumper wires
- Breadboard
Schematic Diagram
For this project you need to wire a PIR motion sensor to your ESP32 board. Follow the next schematic diagram.
In this example, we’re wiring the PIR motion sensor data pin to GPIO 27. You can use any other suitable GPIO. Read ESP32 GPIO Guide.
Telegram Motion Detection with Notifications – ESP32 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-esp32-motion-detection-arduino/
Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
*/
#include <WiFi.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"
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
const int motionSensor = 27; // PIR Motion Sensor
bool motionDetected = false;
// Indicates when motion is detected
void IRAM_ATTR detectsMovement() {
//Serial.println("MOTION DETECTED!!!");
motionDetected = true;
}
void setup() {
Serial.begin(115200);
// 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);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
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 <WiFi.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 = 27; // 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.
void IRAM_ATTR detectsMovement() {
//Serial.println("MOTION DETECTED!!!");
motionDetected = true;
}
setup()
In the setup(), initialize the Serial Monitor.
Serial.begin(115200);
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: ESP32 with PIR Motion Sensor using Interrupts and Timers
Init Wi-Fi
Initialize Wi-Fi and connect the ESP32 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 ESP32 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 ESP32 on-board EN/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 ESP32 board. When motion is detected, a message is sent.
With this bot, you can also use your Telegram account to send messages to the ESP32 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 ESP32 with our resources:
Thanks for reading.
Hi, is this project locally or motion detected can be discovered even if my smartphone and esp32 aren’t connected to the same network (WiFi)
Hi.
The smartphone and ESP32 don’t need to be on the same network.
You’ll be notified no matter where you are.
Regards,
Sara
Hi Sara, after several hours, all is working. Awesome project.
Motion detected, fathbot account ok. But the command /start does’nt works. i have “unrecognized command. Say what” as answer.
Does this command is remove from telegram projects?
Georges
Iphone 11 pro
Hi.
You need to send the start command to the telegram bot you have created, and not the bot father.
Regards,
Sara
Very good projects.
I hope you will look into ESP32-CAM, and send a picture when motion is detected to Telegram.
Thanks.
Yes, it’s coming soon.
Regards,
Sara
Is possible to do the same using micropython?
At the moment I don’t think there’s a library available for MicroPython, but it’s definitely possible to do it
Hi Sara, great tutorial, as ever! If the telegram account is set up on a smart phone is there an easy way to get the very long BotToken onto the PC for adding into the ESP32 code? Or, can the Telegram account be set up from a PC?
Hi Bob, i took a print-screen of it and send it to my laptop. Check twice or more when adding it into the ESP8266 code. But i ‘am also wondering if i make a mistake or not, because i receive no messages on my Telegram bot.
Send It by email to yourself.
I found it more easy to make a new bot on https://web.telegram.org and copy paste it from there. This time it works fine.
Thank you!!!
You’re welcome!
Hi
I have the code uploaded to an ESP32 board, and it all seems to work. The board connects to my wifi and receives a valid IP address. I currently have a switch connected in place of the motion detector output on D27 and when the switch is operated, the “motion detected” message comes up in the serial monitor window. However, I don’t get any notification come up on the phone. I created the Bot and got an ID as instructed in the tutorial. Also the Bot token string. I put these into the sketch in the appropriate places. I can find my account ok in Telegram and I was able to start the Bot ok (I think). I have the desktop app installed as well, and I can send a message from the desktop to the phone. So what is going wrong with the ESP board sending a message to the phone. Any thoughts ?
OK. Ignore that ! Got it. You have to be very VERY careful of the token string. I had mistaken an upper case “O” for a zero … Now that I have put that right, it is sending messages without a problem 🙂
Hello,
I followed your tutorial. I use the ESP32-WROOM-32D hardware.
I experienced a small issue – compiler errors with the JSON library.
I installed version 5 instead of version 6 and code runs like a charm.
Congrats with your work. I am a fan of RNT.
Keep up the good work!
That’s great!
I’m glad you like our projects 😀
Regards,
Sara
Hi Rui and Sara. I have a number of ESP32 cam boards working from your excellent tutorials, and am able to view them on my phone using the Netcam Studio platform. I have also just followed this tutorial to set up a motion detector working through a Telegram bot. I particularly like this platform, and I am very pleased with the way it works. I was wondering as both the node mcu and cam modules both have an ESP32 module on board, and the cam module has a few spare I/O’s, if the motion detect / Telegram code in this tutorial could be combined to both run on the cam board simultaneously. That would give a completely independent motion detect warning via Telegram, and then allow the camera to be opened via Netcam. What do you think ?
Hi
I like to test this Tutorial
– upload seams OK!
– Telegram BOT is open and active
– but afterward I get this message in the Serial-Monitor:
17:03:10.817 -> ets Jun 8 2016 00:22:57
17:03:10.817 ->
17:03:10.817 -> rst:0x1 (POWERON_RESET),boot:0x3 (DOWNLOAD_BOOT(UART0/UART1/SDIO_REI_REO_V2))
17:03:10.817 -> waiting for download
what can be happen? what means,
Important: go to your Telegram account and search for your bot. You need to click “start” on a bot before it can message you.
click “start” where?
Thank you for your help
all the best, regards
Max
Hello Max, it looks like you’ve restarted your ESP32-CAM board while GPIO 0 is connected to GND.
If you restart your ESP32-CAM when GPIO 0 is connected to GND the ESP will be in flashing/downloading/uploading mode.
Remove GPIO 0 from GND, restart your board and it should work now.
Regards,
Rui
Hello Rui & Sara. Thanks for another very good ESP32/Telegram tutorial. I just setup this tutorial with a SparkFun PIR motion sensor (SEN-13285) and it sends a “Motion Detected” signal repeatedly even though the sensor is not in motion. Is there additional coding required to get this working properly? Also, I added a Adafruit SGP30 air quality sensor to your Telegram Environmental tutorial, but I’m unable to receive an air quality data from the sensor. If you have experience with this sensor, would you please tell me the coding necessary to get the data to show up in Telegraph? Thanks for all of your assistance.
Hi.
I haven’t experimented with any of those sensors.
Take a look at Sparkfun’s tutorial for the PIR motion sensor and see if you need to change something to make it works like ours: https://learn.sparkfun.com/tutorials/pir-motion-sensor-hookup-guide
As for the air quality sensor, I haven’t experimented with that either. However, we have this project that you can follow and modify to achieve what you want: https://randomnerdtutorials.com/telegram-request-esp32-esp8266-nodemcu-sensor-readings/
Regards,
Sara
Hi Rui Sara,
I found out that I had the sensor wired incorrectly, so I’m able to detect the sensor motion on Telegram. Thanks for your quick response to my inquiry.
Hi
Thanks for the very interesting script.
Have it installed for my mailbox and it works.
Unfortunately, I can only operate ESP32 with motion detector with battery.
To do this, I need the deep sleep mode.
How can I include it in your script if a loop section is already programmed there?
Is that even possible?
Thanks for all of your assistance.
Hi.
If your ESP will be awaken by the PIR motion sensor, you can put the code to send the message in the setup.
This way, every time it wakes up, it will send a message.
Regards,
Sara
Hi Thanks for the tip.
I still have to change something but now it’s going well.
Best regards
Erni
Hello Sara and Rui
incredible cool projects you are running – helped a lot to spend the lockdowns! 🙂
I wanted to make the ESP Telegram messages a bit more lively with emoijs – the following code works and it is only a single line of code:
bot.sendMessage(CHAT_ID, “\U00002764”, “”); // Emoji Heart
bot.sendMessage(CHAT_ID, “\U0001F920”, “”); // Emoji Cowboy
The length of the Emoji identifier is fixed!
Unicode tables for the emojis can be found e.g. unicode-table.com/en/sets/faces/
Maybe somebody wants to use emoijs – so I share the code… 😉
Greetings
RPI
That’s an excellent idea.
Thank you so much for sharing 😀
Hi. Cool intresting idea. I Like to see the whole code please. Thnx
Hi RPI. Cool intresting idea. I Like to see the whole code please. Thnx
Can Telegram on a device work with a ESP32 that are on the same WIFI but with no internet connection? I want local use only.
Thanks, I appreciate the great tutorials!
Hi.
You need have connection to the internet so that the Telegram App can connect with its servers.
Regards,
Sara
Hello.
I have an issue where I don’t receive any notifications on my phone nor the serial monitor for whether motion has been detected. I am able to receive the “Bot started up” notification, so I have no issues with phone notifications. I have a feeling it might be the “attachinterrupt” function, but I am not really sure what the problem is. I know its not the sensor. I have successfully used 3 motion sensors in another project, so it is not a faulty sensor. I did realize that the pin setup you have has 36 pin, where my ESP32 has 38 pins, so the pin layout is different. For example your 3V3 pin is on the bottom left of the ESP32 module. Mine is on the top right. What would you recommend me do? I feel that just trying each pin would be time consuming and possibly destructive, but effective in narrowing what pin I can and cannot use (That’s if I have an issue with pins at all).
Hi Ryan.
That pin shouldn’t be an issue.
Have you tried using just the PIR sensor with the same pin?
Just to make sure that the PIR works with that pin?
Regards,
Sara
Hello Sara. Thank you for you response. I found my issue. While attempting what you recommended, I found that I could take off the white dome which revealed pin marks. I couldn’t find the markings previously so I tried to go based off of pictures. Basically user error. But its all good now. This is so cool!!!
Dear Sir/Madam Santos,
Will this work with ESP8266 ?
Regards
Yes, it will work with a few modifications.
You can simply follow this tutorial: https://randomnerdtutorials.com/telegram-esp8266-nodemcu-motion-detection-arduino/
Regards,
Sara
This may be a silly question, but can the PIR motion sensor detect motion through a window? For example, the sensor is pointed at a window to detect motion from anyone looking in the window from outside, or passing by outside the window? Thanks
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
Hello guys. Thanks a lot for your instructions. I’m trying this project with VS and PlatformIO. Not sure whether this is an issue, but I’m getting the following error while connecting to WiFi:
[E][WiFiClientSecure.cpp:127] connect(): start_ssl_client: -1
Do you have any advice?
Thank you
I fixed the issue by setting _use_insecure to true in WiFiClientSecure::connect()
I don’t know how does it work for others as I couldn’t find any SSL settings in UniversalTelegramBot code.
Anyway, will work for me for now.
Dear Sara,
Thank you for your excellent tutorials.
I seem to be doing something wrong as I am not getting any messages on Telegram.
All settings are as per your tutorial – created new bot, copied token and pasted it into the code, same with chat_id.
I do get “Motion Detected on the serial monitor.
On Telegram I click on Start when opening the bot but nothing happens, I do not get the “Bot started up” message.
Can you please point me in the right direction?
PS. I also followed your tutorial on “Telegram: Request ESP32/ESP8266 Sensor Readings (Arduino IDE)” but with the same result.
Thanks
Braam
Hi Braam.
Thanks for following our work.
Are you sure you copied the token right? It is quite big and if you didn’t do a direct copy and paste and it very likely that there is a mistake somewhere.
You can use Telegram on your browser to copy the token directly to your code.
I hope this helps.
Regards,
Sara
I too suffered a problem like this at first and spent a long frstrating time trying to get to the bottom of it, and it was indeed a fault with the enterering of the token. I had an “o” in place of a “0”. Once I finally spotted that and corrected it, I had no further problems
Thanks for your advice, Geoff. I copied the token directly from Telegram but it did not solve my problem. The sketch works 100% with a 8266 NodeMcu though.
Much appreciated!
Hi Sara,
Thanks for getting back to me.
I did copy the token from Telegram on my browser initially without success.
I was successful when doing Control Outputs using Telegram – ESP32/ESP8266 Sketch on a ESP8266 NodeMcu.
I do not think the issue is with the token or the chat_id as it works on the other sketch as I said.
Will keep on trying.
OK.
Then, let me know if you find the issue.
Regards,
Sara
Hi Sara,
The same sketch (with obvious modifications) works perfectly on a ESP8266 NodeMcu but will not work on the ESP32. Might be faulty hardware although other (non-Telegram) projects works well with the same ESP32.
Regards
Braam
Hi,
Why the motion sensor is defined as an INPUT_PULLUP instead of just INPUT?
Is there any difference?
Thank you in advance!
Same question here. HC-SR-501 is “normal LOW” and if motion is detected it goes HIGH @ 3.3V. In my understanding ESP32 INPUT_PULLUP has somewhat of 50kOhm pullup resistor and normal LOW needs to drain that ~100uA of current to stay LOW. Is there any reason to pullup HIGH ?
Hi Rui & Sara,
I have created a bot I started the bot and then did run your demo-sketch
but I don’t get any messages
Is there a way to debug the whole process?
I have copy& pasted the token and the message ID
Next thing I did was taking the example-code from the library
https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/blob/master/examples/ESP32/FlashLED/FlashLED.ino
and this worked straight away
So what is the difference between them?
Hi.
Is your PIR motion sensor detecting motion?
Can you double-check that your PIR sensor is working properly?
Regards,
Sara
Hi Rui and Sara,
i was wondering does it take a long time to connect to the wifi network? because mine take way too long to connect.
Hi.
It should connect within a few seconds after starting the program.
Regards,
Sara
Yes I think I might also try this with ESP8266 ….. it would not work with ESP32. I was able to insert all information… bot token chat ID and then watch motion detected on serial monitor but nothing on the Telegram end? I was careful to cut and paste the bot token like others before me have said. Something is not right
Hi, thank you very much for the tutorial
I want to ask, what if the message is not only for one user (#define CHAT_ID “XXXXXXXXXX”) but for all users who added the bottelegram
Hi.
I think the answer for your question is in this tutorial: https://randomnerdtutorials.com/telegram-group-esp32-esp8266/
Regards,
Sara
Hi,
Please help on how to get the TELEGRAM_CERTIFICATE_ROOT ?
Thanks
Hi.
It is included in the library by default.
Make sure you install the library as explained in the tutorial, and the code will compile just fine.
Regards,
Sara
hey thanks for the tutorial
I want to ask if this notification can be timed
for example once every one minute
Hi Rui & Sara,
thanks for the tutorial, I want to ask
Is it possible if the number of messages is limited
Hi.
What do you mean?
I didn’t understand your question.
Regards
Sara
Hello Sara,
thanks for this great piece!
Sorry that I have to bother you with a little problem I have when running the following part:
…
bot.sendMessage(CHAT_ID, “Bot started up”, “”); // Bot started up
}
void loop() {
if (motionDetected) {
bot.sendMessage(CHAT_ID, “Motion detected”, “”);
Serial.println(“Motion Detected”);
motionDetected = false;
…
All seems to work fine. The Bot is showing the message “Bot started up”. The Serial printer shows “Motion Detected” when I move. But the Bot doesn’t show the message “Motion detected”, even though the Bot obviously can receive messages, and the pir works fine as well. I can’t figure out why this happens, because everything else seems to work, except for sending the message to the Bot from the loop. I even copied the bot.sendMessage string that worked from the setup to the loop . And there it didn’t work anymore. Any ideas are appreciated!
Thanks a lot!
I narrowed it a bit down: When commenting out the message “Bot started up” from the setup, the first motion from the loop is sending the message “Motion Detected” which is shown in the Bot, but no further motion causes any new message. So, exactly one message can be sent (or received by the Bot?), whether from the setup or the loop. Each further message is suppressed somehow.
Hello Sara,
thanks for this great piece!
I wonder why I am still struggling with a mysterious problem regarding the following part:
…
bot.sendMessage(CHAT_ID, “Bot started up”, “”); // Bot started up
}
void loop() {
if (motionDetected) {
bot.sendMessage(CHAT_ID, “Motion detected”, “”);
Serial.println(“Motion Detected”);
motionDetected = false;
…
Only the very first message sent by bot.sendMessage is shown in my telegram bot (in this case “Bot started up”). Further messages are not shown anymore. If I suppress the start-up message, the message on the first motion is shown in telegram, but not any further motion message, even though they are shown in the Serial monitor. Do you have any idea what is going on here? I am a bit out of my depth. Thanks a lot!
Armin
Hi.
that’s wierd.
Are you sure your PIR motion sensor is working normally?
Regards,
sara
Hi,
I am not exactly sure about the PIR, as I have seen that it sends motion detections endlessly. But anyway, these should all show up in telegram and only the first one does.
Today I tried your other sketch with the BME280. Same problem here and it seems to come from telegram. Here, the “/start” message from telegram is causing the first action which is working. But no further message (in that case “/reading”) sent from telegram reaches the ESP32.
I helped myself a bit by suppressing the original “/start” message, taking the “/reading” part and calling it “/start” so that the first message sends the weather data, and then resetting the ESP32 every 10 minutes, so that it sends my weather data every 10 minutes automatically to telegram. This works since then “/start” is always the first message of my bot. But I can’t make any further calls from telegram except for this first one.
Hi.
That’s weird.
Try creating another telegram bot and changing your code to use the new bot and see if that solves the issue.
I don’t know what might be causing that weird behavior.
Regards,
Sara
This issue was solved by downgrading the library ESP32 from v2.0.2 to v2.0.1. Then everything works perfect.
Hi, again.
I’m sorry, but I don’t know how to solve that issue.
It isn’t supposed to work like that.
Regards
Sara
Hi Sara,
thanks a lot for your time! I will try a new bot as you suggested (didn’t think of it).
Best regards
Armin
Hi Sara.
I want to reproduce your project but to photograph birds when they enter a feeder.
The first thing was to try to compile the source with IDE without changing anything at all, but it gives this error:
Error compiling for AI Thinker ESP32-CAM board.
I use the IDE 1.8.13
Could you help me to solve it?
I have other sketches for AI Thinker that compile correctly.
Thanks
Hi.
Can you provide more details about the error?
Regards,
Sara
Sorry,
I reinstalled ArduinoJson library and it works correctly now
Thanks. Regards
Josep
I would like to combine this project with the idea of Bot Controll in the ESP32-CAM project.
So the ESP should be in deep sleep to save battery and only checks in the Telegram Bot every x seconds or based on the PIR if a new command (/photo) has been given to the ESP.
So ESP either sends a photo if the PIR was triggered and it is waked by that (already working), or ESP sends a photo after a command /photo was send into the BOT. This is also working (like in your other tutorial for the esp32cam), but unfortunatelly not together with deep sleep.
Everytime the ESP awakes based on the timer and checks the BOT it always gets only one message with /start.
I assume the BOT always sends a /start command at bootup of the ESP and it doesn’t resend all messages that have been send to the BOT during the sleep of the ESP? Any ideas on this?
Hi.
I think the ESP needs to be awake to be able to receive the messages.
I don’t think it will receive older messages.
Regards,
Sara
Hi sara
I set everything up but I don’t get a notification of the movement on my telegram I just get a message “bot started up” I don’t know what the problem is. Please help me because I will submit the project for my graduation in two days.
I am using freenove esp32-wrover-dev but the traffic is not sending in telegram it tells me that the bot started but the traffic is not sending please help
Very good. Now I was wanting to insert another sensor, I messed up the code and I’m not getting it. I want to insert another motion sensor and I can’t.
Hi.
What happens exactly?
You need to provide more details and be more specific.
Otherwise, it is very difficult to find out what might be wrong.
Regards,
Sara
What are the things that I can do in this project?
Hi Sara,
thanks again for this great project which now seems to work more or less fine.
However, I did notice a strange time lag between pressing /photo in the telegram bot and the actual situation that is shown in the received picture. There seems to be a delay of three pictures or so. I tested this with the flash turned on. Then I sent “/photo”, but the next two pictures were still dark. Only the third one showed the enlightened scene. Same thing when turning off the flash (which happens quite immediately). The next two pictures were still bright, and only the third one was dark.
Has this something to do with some kind of picture buffer? I noticed that this also happened when I took the next three pictures after hours. Only the third one was more or less the actual one whereas the former two were taken hours ago.
Do you know some modification of the code that prevents this strange behaviour?
Thanks!
Armin
Hi Sara,
is there a possibility to get the picture in telegram in UXGA resolution? For now, all sent pictures are in a resolution of only 400 x 296 pixels. Or is this a restriction of telegram bots?
Thanks!
Armin
hi there when ever i started complaining code it show me bunch of errors
What errors? Do you have all the required libraries installed?
Regard,s
Sara
Hai Sara, i have tried with esp32 cam and worked, only issue is there is a delay in captured image and the one sent to phone, how to avoid that
Hi.
Add the following line to the camera configurations:
config.grab_mode = CAMERA_GRAB_LATEST;
And use this function:
String sendPhotoTelegram(){
const char* myDomain = “api.telegram.org”;
String getAll = “”;
String getBody = “”;
// Clean previous buffer
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
esp_camera_fb_return(fb); // dispose the buffered image
fb = NULL; // reset to capture errors
// Get fresh image
fb = esp_camera_fb_get();
if(!fb) {
Serial.println(“Camera capture failed”);
delay(1000);
ESP.restart();
}
Let me know if this solves the issue.
Regards,
Sara
Just to mention that this particular code works for an esp32, and that if you’d happen to use a esp8266 you’d have to change a few things i order to get the Telegram part going. Or at least I had to.
You’d declare:
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
and, in setup:
configTime(0, 0, “pool.ntp.org”); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
// client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org. WHICH ONLY WORKS FOR ESP32
// client.setInsecure(); // this actually did nothing in esp8266 case.
And BTW i found this solution in some other Random Nerd Tutorial…
After these changes, it did work as expected.
Hi.
We have a similar tutorial but compatible with the ESP8266.
You can check it on the following link:
https://randomnerdtutorials.com/telegram-esp8266-nodemcu-motion-detection-arduino/
Regards,
Sara
Hi, i change the pir sensor to ultrasonic sensor. ……{“ok”:false,”error_code”:403,”description”:”Forbidden: bot can’t send messages to bots”}
Then i get this message, what it means??
AWESOME example code!
Worked first try 😉
Great!
Hello,
First of all, many thanks for your project and your article, It is superb.
Nevertheless, I’m facing an issue which is a pain for me. I completed everything succesfully (compilation, wifi connection, wiring, etc.) but the interrupt is triggered when no changes un the sensor (I debbuged and no changes in the GPIO input either).
It is triggered in a regular basis and with the same time periods between interrupt calls.
I use esp32-wroom-32 devkit c.
Seeking on the internet I discovered that the built-in wifi interrupts might be triggering the sensor interrupt too. Please, could you support me to solve this annoying issue? Firmware Update? Etc.?
Thank you so much
Hi.
Can you try to use another pin for the interrupt?
Regards,
Sara
Many thanks Sara for your quick response. I used GPIO4, but I also used other pins and the issue remains. Any other hint? Maybe a firmware update or something similar?
Hi.
I think that might be a problem with the hardware or the configuration of the pins.
I don’t think the software might solve the issue.
Regards,
Sara
Hey there, I have followed every step, I can see Motion Detected every half second in serial monitor. But i dont know if esp is connected to wifi or not. Cause Bot is not receiving any messages. I have /start the bot but there is no reply. and no message is coming from esp32 too. Pls help ASAP.
Hi.
Make sure you initialize a conversation with the bot first.
It will only be able to send you notifications if you start a conversation with it first.
Regards,
Sara
Hello Rui & Sara,
after 2 years, I have tried to restart this project, but it is not reporting anything to the bot.
Was there any change from year 2022 and now which might cause this issue? (in year 2022 it was working perfectly)
Thank you.
Hi.
Do you get any issues in the Serial Monitor?
Please note that you need to start a conversation with the boat first (manually), before it can send any messages.
Regards,
Sara