This guide shows how to request ESP32 or ESP8266 NodeMCU sensor readings using Telegram. As an example, we’ll request temperature and humidity readings from a BME280 sensor. You just need to send a message to your Telegram Bot to monitor your sensors or inputs from anywhere in the world. The ESP boards will be programmed using Arduino IDE.
Project Overview
In this tutorial we’ll build a simple project that requests ESP32 or ESP8266 NodeMCU temperature and humidity readings using the Telegram app. We’ll use a BME280 sensor, but you can use any other sensor.
- You’ll create a Telegram bot for your ESP32 or ESP8266 NodeMCU board;
- You can start a conversation with the bot;
- When you send the message /readings to the bot, the ESP board receives the message and responds with the current temperature and humidity readings;
- You can send the /start message to receive a welcome message with the commands to control the board.
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 App
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/ESP8266 will interact with the Telegram bot to receive and handle the messages, and send responses. In this tutorial you’ll learn how to use Telegram to send messages to your bot to request sensor readings from anywhere (you just need Telegram and 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/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 ESP32 and ESP8266 boards using Arduino IDE, so make sure you have them installed in your Arduino IDE.
- Installing the ESP32 Board in Arduino IDE (Windows, Mac OS X, Linux)
- Installing ESP8266 Board in Arduino IDE (Windows, Mac OS X, Linux)
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.15.2.
BME280 Sensor Libraries
To get readings from the BME280 sensor module, we’ll use the Adafruit_BME280 library. You also need to install the Adafruit_Sensor library. Follow the next steps to install the libraries in your Arduino IDE:
1. Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The Library Manager should open.
2. Search for “adafruit bme280 ” on the Search box and install the library.
To use the BME280 library, you also need to install the Adafruit Unified Sensor. Follow the next steps to install the library in your Arduino IDE:
3. Search for “Adafruit Unified Sensor“in the search box. Scroll all the way down to find the library and install it.
After installing the libraries, restart your Arduino IDE.
Parts Required
For this example we’ll get sensor readings from the BME280 sensor. Here’s a list of parts you need to build the circuit for this project:
- ESP32 board (read Best ESP32 dev boards)
- Alternative – ESP8266 board (read Best ESP8266 dev boards)
- BME280 sensor
- Jumper wires
- Breadboard
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Schematic Diagram
The BME280 sensor module we’re using communicates via I2C communication protocol, so you need to connect it to the ESP32 or ESP8266 I2C pins.
BME280 wiring to ESP32
The default ESP32 I2C pins are:
- GPIO 22: SCL (SCK)
- GPIO 21: SDA (SDI)
So, assemble your circuit as shown in the next schematic diagram (Guide for ESP32 with BME280 and ESP32 BME280 Web Server).
Recommended reading: ESP32 Pinout Reference Guide
BME280 wiring to ESP8266 NodeMCU
The default ESP8266 I2C pins are:
- GPIO 5 (D1): SCL (SCK)
- GPIO 4 (D2): SDA (SDI)
Assemble your circuit as in the next schematic diagram if you’re using an ESP8266 board (Guide for ESP8266 NodeMCU with BME280).
Recommended reading: ESP8266 Pinout Reference Guide
Telegram Request Sensor Readings – Code
The following code allows you to request BME280 sensor readings from your ESP32 or ESP8266 board by sending a message to a Telegram Bot. To make it 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-request-esp32-esp8266-nodemcu-sensor-readings/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
*/
#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h> // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// 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"
// Initialize Telegram BOT
#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // your Bot Token (Get from Botfather)
#ifdef ESP8266
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
#endif
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
//Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
// BME280 connect to ESP32 I2C (GPIO 21 = SDA, GPIO 22 = SCL)
// BME280 connect to ESP8266 I2C (GPIO 4 = SDA, GPIO 5 = SCL)
Adafruit_BME280 bme;
// Get BME280 sensor readings and return them as a String variable
String getReadings(){
float temperature, humidity;
temperature = bme.readTemperature();
humidity = bme.readHumidity();
String message = "Temperature: " + String(temperature) + " ºC \n";
message += "Humidity: " + String (humidity) + " % \n";
return message;
}
//Handle what happens when you receive new messages
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
for (int i=0; i<numNewMessages; i++) {
// Chat id of the requester
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
// Print the received message
String text = bot.messages[i].text;
Serial.println(text);
String from_name = bot.messages[i].from_name;
if (text == "/start") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following command to get current readings.\n\n";
welcome += "/readings \n";
bot.sendMessage(chat_id, welcome, "");
}
if (text == "/readings") {
String readings = getReadings();
bot.sendMessage(chat_id, readings, "");
}
}
}
void setup() {
Serial.begin(115200);
#ifdef ESP8266
configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
#endif
// Init BME280 sensor
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
#ifdef ESP32
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
#endif
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
}
void loop() {
if (millis() > lastTimeBotRan + botRequestDelay) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
}
The code is compatible with ESP32 and ESP8266 NodeMCU boards. The code will load the right libraries accordingly to the selected board.
How the Code Works
This section explain how the code works. Continue reading or skip to the Demonstration section.
Start by importing the required libraries.
#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.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 User ID
Insert your user ID. The one you’ve got from the IDBot.
#define CHAT_ID "XXXXXXXXXX"
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)
Create a new WiFi client with WiFiClientSecure.
WiFiClientSecure client;
Create a bot with the token and client defined earlier.
UniversalTelegramBot bot(BOTtoken, client);
The botRequestDelay and lastTimeBotRan are used to check for new Telegram messages every x number of seconds. In this case, the code will check for new messages every second (1000 milliseconds). You can change that delay time in the botRequestDelay variable.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
BME280 Object
Create an Adafruit_BME280 called bme. This creates an I2C object on the default ESP I2C pins.
Adafruit_BME280 bme;
getReadings()
The getReadings() function requests temperature and humidity from the BME280 sensor and returns the results as a string variable that we can send to the Telegram bot.
String getReadings(){
float temperature, humidity;
temperature = bme.readTemperature();
humidity = bme.readHumidity();
String message = "Temperature: " + String(temperature) + " ºC \n";
message += "Humidity: " + String (humidity) + " % \n";
return message;
}
To learn more about interfacing the BME280 sensor with the ESP32 and ESP8266, read:
- ESP32 with BME280 Sensor using Arduino IDE (Pressure, Temperature, Humidity)
- ESP8266 with BME280 using Arduino IDE (Pressure, Temperature, Humidity)
handleNewMessages()
The handleNewMessages() function handles what happens when new messages arrive.
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
It checks the available messages:
for (int i=0; i<numNewMessages; i++) {
Get the chat ID for that particular message and store it in the chat_id variable. The chat ID identifies who sent the message.
String chat_id = String(bot.messages[i].chat_id);
If the chat_id is different from your chat ID (CHAT_ID), it means that someone (that is not you) has sent a message to your bot. If that’s the case, ignore the message and wait for the next message.
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
Otherwise, it means the message was sent from a valid user. So, we’ll save it in the text variable and check its content.
String text = bot.messages[i].text;
Serial.println(text);
The from_name variable saves the name of the sender.
String from_name = bot.messages[i].from_name;
If it receives the /start message, we’ll send the valid commands to control the ESP32/ESP8266. This is useful if you happen to forget what are the commands to control your board.
if (text == "/start") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following command to get current readings.\n\n";
welcome += "/readings \n";
bot.sendMessage(chat_id, welcome, "");
}
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 = "")
In our example, we’ll send the message to the ID stored on the chat_id variable (that corresponds to the person who’ve sent the message) and send the message saved on the welcome variable.
bot.sendMessage(chat_id, welcome, "");
If it receives the /readings message, get the current sensor readings by calling the getReadings() function. Then, simply send the message.
if (text == "/readings") {
String readings = getReadings();
bot.sendMessage(chat_id, readings, "");
}
setup()
In the setup(), initialize the Serial Monitor.
Serial.begin(115200);
If you’re using the ESP8266, you need to use the following line:
#ifdef ESP8266
client.setInsecure();
#endif
In the Universal Telegram Bot Library library examples for the ESP8266, it says: “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“.
Init BME280
Initialize the BME280 sensor.
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
Init Wi-Fi
Initialize Wi-Fi and connect the ESP 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..");
}
loop()
In the loop(), check for new messages every second.
void loop() {
if (millis() > lastTimeBotRan + botRequestDelay) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
}
When a new message arrives, call the handleNewMessages function.
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
That’s pretty much how the code works.
Demonstration
Upload the code to your ESP board, open the Tools menu > 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 ESP on-board EN/RST button so that it starts running the code. Then, open the Serial Monitor to check what’s happening in the background.
Go to your Telegram account and open a conversation with your bot. Send the following commands and see the bot responding:
- /start shows the welcome message with the valid commands.
- /readings returns the current temperature and humidity readings from the BME280 sensor.
At the same time, on the Serial Monitor, you should see that the ESP32 or ESP8266 is receiving the messages.
If you try to interact with your bot from another account, you’ll get the the “Unauthorized user” message.
Wrapping Up
In this tutorial you’ve learned how to create a Telegram Bot to interact with the ESP32 or ESP8266 NodeMCU boards. With this bot, you can use your Telegram account to monitor sensors and control outputs.
We’ve shown you a simple example on how to request sensor readings from a BME280 sensor. The idea is to modify the project to add more commands to execute other tasks. For example, you can send a Telegram message to control outputs or send a message to your account when motion is detected.
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.
We hope you’ve found this project interesting. Learn more about the ESP32 and ESP8266 with our resources:
- Learn ESP32 with Arduino IDE (eBook + Video Course)
- Home Automation using ESP8266
- More ESP32 projects and tutorials…
- More ESP8266 projects and tutorials…
Thanks for reading.
/getid does not work
Did you open the correct IDBot window? You must search for idbot and open this exact conversation (it has a blue fingerprint image):
https://randomnerdtutorials.com/wp-content/uploads/2020/06/Telegram-ID-Bot.png
Thank you so much Rui and Sara for your great effort in providing great and comprehensive tutorials. We really appreciate your immense effort.
You’re welcome! Thanks for reading them
I thank both of you, since I was waiting for some project like this for a while… I was managing with RPi but this way we same power and an intermediate.
Are you going to have this project in micropython also? Thank you.
At the moment we don’t plan to create these guides for MicroPython, but we might do it in the future. Thanks for the suggestion!
I assume your page has a simple typing error …
“We’re using ArduinoJson library version 6.5.12.”
6.5.12 does not exist.
6.15.2 does, and that’s what is shown on your images
Hi.
You’re right.
Thanks for telling us. It is fixed now.
Regards,
Sara
Dear Sara, Rui,
Again a nice tutorial!
As i1m working with ESP8266 (wemos mini r1d2) modules to aquire data by tcp socket, i really wanted to make this project (to learn advance solutions) . But unfortunately it doesn’t work for me:
there was no problem with telegram, i could create newbot, get token, get my id etc….
there was no problem to install telegram library to arduino IDE as you said,
i couldn’t install arduinoJson by library manager, but i downloaded the ZIP by the link what you shared in the description this is:ArduinoJson VERSION 6.15.1 and i could install it,
after i upload the program, there was no response to query: /readings or /start, even nothing comes by serial monitor (means: got response or something)
reason of this i combined your code to my code, so my existing sketch, where my device create a webpage, showing up temp and humidity data. (to ensure there is no network problem)
my server is:
WifiServer Server(80), and WiFiClient client = server.available(); ,
AND your client is:
WiFiClient client2;
UniversalTelegramBot bot(BOTtoken, client2); ,
my server runs OK, (so means network connection ok,) but your code doesn’t response. unfortunately i can not trace where could be wrong, as no such tracing possibilities in the code, what i know the main loop runs every second is OK (I put there a Serial.print to ensure that routine check bot.getupdates every sec.)
What do you think what else could i check to be able to run?
Thanks your reply in advance,
No found ESP8266WiFi.h PLS HELP!!!
Hi.
Make sure you have the ESP8266 board installed in your Arduino IDE.
You can follow this tutorial: https://randomnerdtutorials.com/how-to-install-esp8266-board-arduino-ide/
Regards,
Sara
Your programs don’t work!!! There is no ESP8266wifi library And the telegram bot does not issue an id ! I hope you are checking the code, because it doesn’t work.
Hi.
When you say it doesn’t work, what happens?
We test all our codes before publishing them.
Regards,
Sara
Sorry, I don’t understand why my program didn’t work. The bot didn’t start. It looks like the API was incorrectly specified. You need to repeat the build and programming again.
Thank you so much for your tutorial. It helps me a lot.
Thank you 🙂
I’m glad it did.
Regards,
Sara
Sorry, all ok!!!
I’m from Russia, so it’s hard to talk. I must try again to reassemble everything.
When I search created bot, I found,
I start it with /start
No response
Then I tried, /hetu command
/getid command not working for me.
I tried it so many times ,
Even I delete created bot & create new bot so many times, but failed.
Could not found my mistake.
Hi.
Without further information, it’s very difficult to find out what might be wrong.
Regards,
Sara
I tried your esp 8266 temp readings, it is getting compiled but during uploading it shows An error occurred while uploading, pls give your clue to fix this problem.
S.Yogaraja
India.
What’s the error?
exit status 1
Erro compilando para a placa NodeMCU 1.0 (ESP-12E Module)
Este relatório teria mais informações com
“Mostrar a saida detalhada durante a compilação”
opção pode ser ativada em “Arquivo -> Preferências”
Pode dar mais detalhes sobre o erro?
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
What is this problem, pls help me
Hi.
Can you give more information about the error?
Regards,
Sara
Hello! Thanks a lot for your hard work! Everything works! Can you read the pressure from the BME280 sensor? Thanks!
Thanks! Added pressure reading function!
hi, please share your sketch. Thanks
Thank you very much! Added pressure, everything works!
hello, could you provide a sketch? For some reason this sketch doesn’t work for me.
Many thanks to Rua and Sara for the great effort. But does this description work on Telegram on 16: 12: 2020 ???? hey no !!!!
Hi.
What do you mean?
Regards,
Sara
Hi!
I have tried running the program. Unfortunately, I got an error message shown “TELEGRAM_CERTIFICATE_ROOT” was not declared in this scope. What should I do to solve this error? Thank you very much & have a nice day ahead!
Hi.
Make sure that you have the latest version of the Telegram library installed.
Regards,
Sara
Thank you Sara.
I have installed the UniversalTelegramBot by Brian Lough version 1.3.0 but in the drop down list of version, there’s only version 1.0.0 and 1.1.0. Which one should I choose?
Hi.
You should use version 1.3.0.
Install it by following the instructions in the tutorial.
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.
Hi Sara.
I’ve installed the mentioned library already.
I still facing the same problem.
The error is being highlighted at line X509List Cert(TELEGRAM_CERTIFICATE_ROOT);
How can I declare the TELEGRAM_CERTIFICATE_ROOT. Can I do #define TELEGRAM_CERTIFICATE_ROOT ?
The TELEGRAM:CERTIFICATE_ROOT is defined in the library files.
So, there shouldn’t be necessary to include it that way.
Make sure that Arduino IDE is using the latest version of the library and not an old version. You may need to delete the old versions if that’s the case.
Regards,
Sara
Hi Sara!
Again with the same error. Now that my library ESP8266WiFi is the latest version 3.0.0 and my UniversalTelegramBot is version 1.3.0. However, upon compiling the code, I still facing the same issue like the previous error. What should I check again in detail to resolve this issue? Thank you again Sara.
Hi.
At this point, I’m out of ideas of what might be causing your issue.
Maybe it is better to try to post an issue on the library GitHub issues page: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/issues
Regards,
Sara
Alright thank you Sara. Thank you for helping me out 😄 have a nice day ahead!
hi there,
found a problem which i cant solve. when requesting /readings I get an old reading from last time I did the request. This changes when issuing /readings for the 2nd time. Then I get an actual reading. how come?
rgds
First: thanks for another great tutorial!
I’m “merging” this example that uses Telegram to request sensor readings and your own OTA w/Arduino (https://randomnerdtutorials.com/esp32-ota-over-the-air-arduino/).
Response becomes slow and sometimes hangs for a long time. I’m guessing that the ESP32 has a tough time listening to port 80 for AsyncWebServer requests while at the same time running a loop to check for new Telegram messages? Would it be more efficient to send the Telegram message from a web server instead? (i.e. since it’s already running AsynWebServer).
Thanks!
+1 same problem
Hi.
Try using the AsyncTelegram library: https://github.com/cotestatnt/AsyncTelegram
Regards,
Sara
Hello Sara & Rui,
is it possible to continuously redirect answers to request /reading to database or Excel?
Tommy
Hi.
Yes, that is possible.
But, I don’t have any code combining both scenarios.
Regards,
Sara
Hi,
I want to restart my ESP32 on command.
When it starts new, it repeats the last command endlessly.
bot.closeClient() does not work.
Do you have an idea?
thank you
It worked, but I don’t understand how my ESP8266 code knew to talk to my “Lab” bot (I only had one bot name, but what if I had had two?). For example, what if I create a new bot called “Lab2”. I assume my chat ID and token will be the same, so how would I connect a second ESP8266 to “Lab2”. I don’t see that connection in the code.
I guess I’m not quite clear on why I have an address of @XXXX_bot and under (?) that I have a bot named “Lab”. The distinction escapes me.
Oops, sorry. User name in above comment is @XXXXX_bot and the bot is “Lab”. So I make “Lab2” bot and get a new token and had to provide a new user name, eg, @XXXXX1_bot. So I assume it’s the token that is making the new connection from the second ESP8266 and Lab2?
Does this mean I have to open a new telegram window to talk to Lab2? I was thinking I could just send a different command, eg, “readings2” to see the data from the second ESP8266.
hello,
In the monitor I receive this
Connecting to WiFi..
192.168.1.32
got response
handleNewMessages
1
/start
In the telegram : Welcome, Marc.
Use the following command to get current readings.
/readings
But when I click on /readings, I don’t receive sensors values.
Could you advice me ?
Thanks,
marc
Hi.
Can you provide more details about what happens?
Does the ESP32 receive the message? What do you see on the Serial Monitor?
Regards,
Sara
I have the same Problem.
Serial output is ok, but the return value is just empty.
The message I receive from the ESP contains the message but without the temperature.
Hi Sara
I am using ESP32
I have Telegram ESP32 and ESP8266 Control GPIOs and LEDs working correctly.
I also have Telegram: Request ESP32/ESP8266 Sensor Readings working perfectly. I then successfully added multiple DS temperature sensors.
My problem is, as soon as I try and merge the two, the control command does not switch the LED.
Are you able to advise?
I receive the response “LED state is on” but the pin state does not change.
This is included correctly:
//Control
const int ledPin = 2;
bool ledState = LOW;
The responses are correct
if (text == “/conreadings”) {
String conreadings = requestTemperatures();
bot.sendMessage(chat_id, conreadings, “”);
}
if (text == "/led2_on") {
bot.sendMessage(chat_id, "LED state set to ON", "");
ledState = HIGH;
digitalWrite(ledPin, ledState);
}
but the pin state does not go HIGH.
Hi I have installed Telegram on my moby and it seems to work properly with the Node-RED Telegram add in.
I have tried both your projects, one to flash the LED and one to read a BME sensor or actually dummy random values I created. Both work but not consistently or reliably. I have tried using a Wemos D1 Mini and a basic ESP12E. The code complies and runs on the ESP. however, when I send /start it sometimes takes several attempts before the ESP responds to the command, likewise if I sent /readings the esp doesn’t always respond. I have tried the ESP’s on USB and a wall wart so it isn’t a power issue, RSSI is around -50 so it isn’t a weak signal. The Node-RED version also works immediately too. I am using platformIO BTW.
Does anyone have any idea why the ESP doesn’t repond to each Telegram command?
Another thing I discovered is that to get ones ID the command is @my_id_bot in the message box, so it seems some commands have changed.
For the benefit of others I also tried the CTbot library for the ESP8266 / ESP32. It is broken and the ESP826 devices crash. I tried it on platformIO and Arduino IDE 2.0.3.
Hi.
How often do you make requests?
Do you get any information on the serial monitor when you make the commands and it doesn’t respond?
Regards,
Sara
Hi Sara
I installed telegram “Request ESP32/ESP8266 Sensor Readings” and it works perfectly.
I then installed a second sketch to send commands and light a LED which also works as designed.
My problem
I combined the relevant parts of the command sketch to the readings sketch.
The readings continue to work.
When I send a command the command appears to go through, it is reported as being received through the comm port but the output pin state does not change.
Are you able to post a telegram sketch that includes readings and commands?
Hi.
This example includes readings and commands: https://randomnerdtutorials.com/esp32-cam-shield-pcb-telegram/
It’s with the ESP32-CAM, but you can use it as a reference to see how to combine the different features.
Regards,
Sara
Good morning Sara,
I have a doubt about reading the temperature via telegram with ESP32 and DHT22.
How can I configure the reading with only one decimal digit?
With the print on the led display it’s easy but with telegram I didn’t succeed.
Thank you
giuseppe
Hi Sara,
I followed in a meticulous way your clear instructions and I copied your code but when I run the code it just stops after printing in the serial monitor
Connecting to WiFi.. and the IP address
and when I access Telegram after /start and/readings nothing happens
I verified several times both the CHAT_ID and the API_TOKEN but they are correct
Could you help me ? Thanks
Bruno
Hi.
If nothing happens, it may probably be related to the chat ID or the API Token.
Additionally, make sure you’re sending the telegram messages to the right BOT.
Regards,
Sara
Hello. Tell me, please, is there any command that allows you to take readings from the sensor every half hour and the bot sends messages?
Hi.
You just need to add a new timer to your code
const unsigned long messageInterval = 180000; //This is half an hour
unsigned long lastMessageTime = 0;
Then, add something like this to the loop() – i haven’t tested it, but the logic is this:
void loop() {
unsigned long currentTime = millis();
if (currentTime – lastMessageTime >= messageInterval) {
String readings = getReadings();
bot.sendMessage(CHAT_ID, readings, “”);
lastMessageTime = currentTime;
}
I hope this helps.
Regards,
Sara
Thank you very much, everything works!
Hi Sara,
this beautyful program does not work since ArduinoJson was updated to V.7.0.0. Restoring the last v.6.x.x solves the problem.
hello!thanks for the tutorial.i would like to know why is telegram displaying the temperature message twice after i send one “/readings” message.