Get Sensor value Notification in Telegram BOT

Modern Gaming Cover YouTube Channel Art (1)
This content provide you Experience

In this blog you will know how to get notification in telegram bot using ESP32 or ESP8266.

Getting sensor values in a Telegram bot using ESP8266 has many benefits, including:

Real-time monitoring: With sensor values integrated into your Telegram bot, you can easily monitor the data in real-time from anywhere, anytime. This can be especially useful for applications that require constant monitoring, such as environmental monitoring, weather monitoring, and industrial automation.

Remote control: By integrating sensor values into your Telegram bot, you can also control devices remotely. For example, if you have a temperature sensor in your greenhouse, you can use your Telegram bot to turn on or off the heating system based on the temperature readings.

User-friendly interface: Telegram is a widely used messaging platform with a simple and user-friendly interface. Integrating sensor values into Telegram bots can make it easier for users to access data and control devices from their mobile devices or desktops.

Customizability: Telegram bots are highly customizable and can be tailored to meet specific requirements. With the ESP8266 microcontroller, you can design custom firmware to suit the specific needs of your project, such as sending notifications or alerts when certain thresholds are reached.

Low-cost solution: The ESP8266 is a low-cost, high-performance microcontroller that can be used to collect and transmit sensor data to a Telegram bot. This makes it a cost-effective solution for small-scale projects that require real-time monitoring and remote control capabilities.


Here are the steps to create a new bot in Telegram:

1- Open the Telegram app or visit the Telegram website ( and log in with your account.

2- In the search bar, type “BotFather” and select the correct result that appears. BotFather is a bot created by Telegram that allows users to create and manage bots.

3- Click on the “START” button to start a conversation with BotFather.

4- Type “/newbot” and press enter. BotFather will then prompt you to enter a name for your new bot.

5- Type in a name for your bot, followed by “_bot”. This is the username that your bot will use, and it must be unique. For example, if you want to name your bot “MyBot”, the username should be “MyBot_bot”.

6- BotFather will then provide you with a token for your bot. This token is a unique identifier that you will use to authenticate and communicate with your bot. Copy and save this token in a secure location.

Now search for “IDBot” in search bar

To get chat id of your telegram type “/getid” and copy the id and keep it.

Code for Touch sensor

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

// Replace with your network credentials
const char* ssid = "your ssid";
const char* password = "Password";

// Initialize Telegram BOT

// 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

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
void setup() {
  delay(1000); // give me time to bring up serial monitor
  Serial.println("ESP32 Touch Test");

    // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");

  WiFi.begin(ssid, password);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for
  while (WiFi.status() != WL_CONNECTED) {

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

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

void loop() {
  Serial.println(touchRead(4));  // get value of Touch 0 pin = GPIO 4
  if (touchRead(4)<=10)
    bot.sendMessage(CHAT_ID, "Touch Detected", "");
    Serial.println("Humidity Updated In percentage");

Code for sensor value update

#include <Arduino.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials
#define WIFI_SSID "Your wifi ssid"
#define WIFI_PASSWORD "your wifi password"

// Insert Firebase project API Key

// Insert Authorized Username and Corresponding Password
#define USER_EMAIL "your@email"
#define USER_PASSWORD "Your password3"

// Insert RTDB URLefine the RTDB URL

// Define Firebase objects
FirebaseData stream;
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

// Variable to save USER UID
String uid;

// Variables to save database paths
String databasePath;
String tempPath;
String humPath;
String presPath;
String listenerPath;

float Reading1;
float Reading2;
float Reading3;

//OLED Display
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

// Timer variables (send new readings every other minute)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 1000;

// Declare outputs
const int output1 = 2;
const int output2 = 12;
const int slider1 = 13;
const int slider2 = 14;

// Variable to save input message
String message;

// Setting PWM properties
const int freq = 5000;
const int slider1Channel = 0;
const int slider2Channel = 1;
const int resolution = 8;

// Initialize OLED
void initOLED(){
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));

// Display messag on OLED display
void displayMessage(String message){

// Initialize WiFi
void initWiFi() {
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {

// Write float values to the database
void sendFloat(String path, float value){
  if (Firebase.RTDB.setFloat(&fbdo, path.c_str(), value)){
    Serial.print("Writing value: ");
    Serial.print (value);
    Serial.print(" on the following path: ");
    Serial.println("PATH: " + fbdo.dataPath());
    Serial.println("TYPE: " + fbdo.dataType());
  else {
    Serial.println("REASON: " + fbdo.errorReason());

// Callback function that runs on database changes
void streamCallback(FirebaseStream data){
  Serial.printf("stream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\n\n",
  printResult(data); //see addons/RTDBHelper.h

  // Get the path that triggered the function
  String streamPath = String(data.dataPath());

  /* When it first runs, it is triggered on the root (/) path and returns a JSON with all key
  and values of that path.So, we can get all values from the database and updated the GPIO
  states, PWM, and message on OLED*/
  if (data.dataTypeEnum() == fb_esp_rtdb_data_type_json){
    FirebaseJson *json =<FirebaseJson *>();
    FirebaseJsonData result;
    if (json->get(result, "/digital/" + String(output1), false)){
      bool state =<bool>();
      digitalWrite(output1, state);
    if (json->get(result, "/digital/" + String(output2), false)){
      bool state =<bool>();
      digitalWrite(output2, state);
    if (json->get(result, "/message", false)){
      String message =<String>();
    if (json->get(result, "/pwm/" + String(slider1), false)){
      int pwmValue =<int>();
      ledcWrite(slider1Channel, map(pwmValue, 0, 100, 0, 255));
    if (json->get(result, "/pwm/" + String(slider2), false)){
      int pwmValue =<int>();
      ledcWrite(slider2Channel, map(pwmValue, 0, 100, 0, 255));

  // Check for changes in the digital output values
  if(streamPath.indexOf("/digital/") >= 0){
    // Get string path lengh
    int stringLen = streamPath.length();
    // Get the index of the last slash
    int lastSlash = streamPath.lastIndexOf("/");
    // Get the GPIO number (it's after the last slash "/")
    // UsersData/<uid>/outputs/digital/<gpio_number>
    String gpio = streamPath.substring(lastSlash+1, stringLen);
    Serial.print("DIGITAL GPIO: ");
    // Get the data published on the stream path (it's the GPIO state)
    if(data.dataType() == "int") {
      bool gpioState = data.intData();
      Serial.print("VALUE: ");
      //Update GPIO state
      digitalWrite(gpio.toInt(), gpioState);

  // Check for changes in the slider values
  else if(streamPath.indexOf("/pwm/") >= 0){
    // Get string path lengh
    int stringLen = streamPath.length();
    // Get the index of the last slash
    int lastSlash = streamPath.lastIndexOf("/");
    // Get the GPIO number (it's after the last slash "/")
    // UsersData/<uid>/outputs/PWM/<gpio_number>
    int gpio = (streamPath.substring(lastSlash+1, stringLen)).toInt();
    Serial.print("PWM GPIO: ");
    // Get the PWM Value
    if(data.dataType() == "int"){
      int PWMValue = data.intData();
      Serial.print("VALUE: ");
      // Set the duty cycle (PWM) on the corresponding channel
      if (gpio == slider1){
        ledcWrite(slider1Channel, map(PWMValue, 0, 100, 0, 255));
      if (gpio == slider2){
        ledcWrite(slider2Channel, map(PWMValue, 0, 100, 0, 255));

  // Check for changes in the message
  else if (streamPath.indexOf("/message") >= 0){
    if (data.dataType() == "string") {
      message = data.stringData();
      Serial.print("MESSAGE: ");
      // Print on OLED
  //This is the size of stream payload received (current and max value)
  //Max payload size is the payload size under the stream path since the stream connected
  //and read once and will not update until stream reconnection takes place.
  //This max value will be zero as no payload received in case of ESP8266 which
  //BearSSL reserved Rx buffer size is less than the actual stream payload.
  Serial.printf("Received stream payload size: %d (Max. %d)\n\n", data.payloadLength(), data.maxPayloadLength());

void streamTimeoutCallback(bool timeout){
  if (timeout)
    Serial.println("stream timeout, resuming...\n");
  if (!stream.httpConnected())
    Serial.printf("error code: %d, reason: %s\n\n", stream.httpCode(), stream.errorReason().c_str());

void setup(){

  // Init BME sensor, OLED, and WiFi

  // Initialize Outputs
  pinMode(output1, OUTPUT);
  pinMode(output2, OUTPUT);

  // configure PWM functionalitites
  ledcSetup(slider1Channel, freq, resolution);
  ledcSetup(slider2Channel, freq, resolution);
  // attach the channels to the GPIOs to be controlled
  ledcAttachPin(slider1, slider1Channel);
  ledcAttachPin(slider2, slider2Channel);

  // Assign the api key (required)
  config.api_key = API_KEY;

  // Assign the user sign in credentials = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  // Assign the RTDB URL (required)
  config.database_url = DATABASE_URL;


  // Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

  // Assign the maximum retry of token generation
  config.max_token_generation_retry = 5;

  // Initialize the library with the Firebase authen and config
  Firebase.begin(&config, &auth);

  // Getting the user UID might take a few seconds
  Serial.println("Getting User UID");
  while ((auth.token.uid) == "") {

  // Print user UID
  uid = auth.token.uid.c_str();
  Serial.print("User UID: ");

  // Update database path with user UID
  databasePath = "/UsersData/" + uid;

  // Define database path for sensor readings
  tempPath = databasePath + "/sensor/Reading1"; // --> UsersData/<user_uid>/sensor/Reading1
  humPath = databasePath + "/sensor/Reading2"; // --> UsersData/<user_uid>/sensor/Reading2
  presPath = databasePath + "/sensor/Reading3"; // --> UsersData/<user_uid>/sensor/Reading3

  // Update database path for listening
  listenerPath = databasePath + "/outputs/";

  // Streaming (whenever data changes on a path)
  // Begin stream on a database path --> UsersData/<user_uid>/outputs
  if (!Firebase.RTDB.beginStream(&stream, listenerPath.c_str()))
    Serial.printf("stream begin error, %s\n\n", stream.errorReason().c_str());

  // Assign a calback function to run when it detects changes on the database
  Firebase.RTDB.setStreamCallback(&stream, streamCallback, streamTimeoutCallback);


void loop(){
  // Send new readings to database
  if (Firebase.ready() && (millis() - sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
    sendDataPrevMillis = millis();

    // Get latest sensor readings
    Reading1 = random(1,100);
    Reading2 = random(100,200);
    Reading3 = random(200,300);

    // Send readings to database:
    sendFloat(tempPath, Reading1);
    sendFloat(humPath, Reading2);
    sendFloat(presPath, Reading3);

Leave a Comment

Your email address will not be published. Required fields are marked *

Related post