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>
// Replace with your network credentials
const char* ssid = “realme 3i”;
const char* password = “YADAV ji”;
// Initialize Telegram BOT
#define BOTtoken “2053093088:AAFWV-vij7S8TVZiM8nO5pwH8m9RA13yMvY” // 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 “1150945947”
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, “t.me/Sensorya_bot.”); // 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(1150945947, “Bot started up”, “”);
}
void loop() {
if(motionDetected){
bot.sendMessage(1150945947, “Motion detected!!”, “”);
Serial.println(“Motion Detected”);
motionDetected = false;
}}
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.