In this project you use Telegram to contact your ESP8266 to check the current temperature. As soon as your ESP8266 receives your request, it requests the current temperature from the BMP180 sensor and sends it to your smartphone.
This project is the third part of a series and builds up on the previous projects. In this article you will find everything you need to set up and the right sketch; however, we will not discuss all parts of the code. If you want to know more details, please have a look at the following projects:
If you have not yet created a project with Telegram, first learn how to create a Telegram bot.
Beginner
1 – 2 hours
ca. $12
For this project you need (quantities see description):
The set up of the project
If you set up the previous project, you don’t have to do anything else on the hardware side – you can simply continue using your setup here. 🙂
The sketch has changed a lot:
The sketch
Copy the following sketch into your Arduino IDE, complete your data and load it onto your ESP8266
/*
Request the temperature with Telegram - polluxlabs.net
*/
//Libraries
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <Wire.h>
#include <Adafruit_BMP085.h>
//WiFI Credentials
const char* ssid = "NETZWERKNAME";
const char* password = "PASSWORT";
//Initialize Telegram Bot
#define botToken "TOKEN" //Token from the Botfather
//Your UserID
#define userID "USERID"
WiFiClientSecure client;
UniversalTelegramBot bot(botToken, client);
Adafruit_BMP085 bmp;
//Variable for the temperature
float temp;
//Variable for the number of requests
int numNewRequests;
//Variable for the string of the request
String text = "";
//UserID of Sender
String chat_id = "";
//Name of Sender
String from_name = "";
//Variable for your Welcome String
String welcome = "";
//Function for new requests
void handleNewRequests(int numNewRequests) {
for (int i = 0; i < numNewRequests; i++) { //loops through new requests
//Checks if the sender of the message is you
chat_id = String(bot.messages[i].chat_id);
if (chat_id != userID) {
bot.sendMessage(chat_id, "You aren't authorized!", "");
continue;
}
//Save message
text = bot.messages[i].text;
Serial.println(text);
from_name = bot.messages[i].from_name;
if (text == "/start") {
welcome = "Welcome, " + from_name + ".\n";
welcome += "Use these commmands: \n\n";
welcome += "/measure \n";
bot.sendMessage(chat_id, welcome, "");
bot.sendMessage(chat_id, "http://gph.is/2aLXZ8H", "");
}
if (text == "/measure") {
temp = bmp.readTemperature();
bot.sendMessage(chat_id, "Temperature: " + String(temp) + " ºC", "");
}
}
}
void setup() {
Serial.begin(115200);
client.setInsecure();
//Connect to WiFi
Serial.print("Connecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println("");
Serial.println("Connected!");
if (!bmp.begin()) {
Serial.println("Sensor not found - Check connections.");
while (1) {}
}
}
void loop() {
//check if there is a new request
int numNewRequests = bot.getUpdates(bot.last_message_received + 1);
while (numNewRequests) { //is executed if numNewRequests == 1
Serial.println("Request received");
handleNewRequests(numNewRequests);
numNewRequests = bot.getUpdates(bot.last_message_received + 1);
}
delay(1000);
}
What is new in this sketch?
In the two previous projects, your ESP8266 only sent messages, but in this project, it is waiting for a message from you – which it then answers itself with the current temperature.
To do this, your ESP8266 – in contrast to the previous projects – must be connected to your Wi-Fi at all times. For this reason, the code with which you establish the connection goes directly into the setup function:
Serial.print("Connecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println("");
Serial.println("Connected!");
Now let’s look directly into the loop. There your ESP8266 checks every 1000 milliseconds whether there is a new request:
int numNewRequests = bot.getUpdates(bot.last_message_received + 1);
If this is the case, the number of existing requests is stored in the variable numNewRequests using the function bot.getUpdates() (normally a 1, but theoretically there can be more than one).
This in turn starts the following While-Loop, which calls the function handleNewRequests() as often as requests are to be “processed”. In this loop the variable
while (numNewRequests) {
handleNewRequests(numNewRequests);
numNewRequests = bot.getUpdates(bot.last_message_received + 1);
}
The function handleNewRequests()
Let’s get to the core of the sketch. This function
handleNewRequests(numNewRequests);
When the function is declared, this variable reappears in order to be processed immediately. This time you iterate with a for-loop over the number of requests to process them one by one:
void handleNewRequests(int numNewRequests) {
for (int i = 0; i < numNewRequests; i++) {
Within the Loop, a very important check takes place first – namely whether the request comes from an authorized user (i.e. you) at all. For this purpose you store the
Then you check if it matches your own User ID. If this is not the case, the sender receives a corresponding message and the For-Loop is aborted with
chat_id = String(bot.messages[i].chat_id);
if (chat_id != userID) {
bot.sendMessage(chat_id, "You aren't authorized!", "");
continue;
}
However, if the request comes from you, you save its text content and the name of the sender (again, yours):
text = bot.messages[i].text;
from_name = bot.messages[i].from_name;
Only two if statements are still missing. When you start your Telegram bot for the first time, you do this with the text
Here again strings are concatenated, this time with the operator +=, which simply adds more text to the variable welcome. Also note: You can insert a line break using
At the end of the statement you will find the function bot.sendMessage() again, which you already know. It appears here twice: Once to send the string
if (text == "/start") {
welcome = "Welcome, " + from_name + ".\n";
welcome += "Use these commands to request the temperature: \n\n";
welcome += "/measure \n";
bot.sendMessage(chat_id, welcome, "");
bot.sendMessage(chat_id, "http://gph.is/2aLXZ8H", "");
}
The second query deals with the request /measure, which should be answered with the current temperature. You already know this from previous projects:
if (text == "/measure") {
temp = bmp.readTemperature();
bot.sendMessage(chat_id, "Temperature: " + String(temp) + " ºC", "");
}
And that was it. In this lesson, you learned how to not only send messages from your ESP8266 to your Telegram bot, but also retrieve sensor data from there.
What’s next?
Of course you can request not only the temperature. The sensor BMP180 can also detect the air pressure. The successor BMP280 even measures the humidity. Create e.g. a weather station, where you request the current data from a distance.
Another possibility is a moisture sensor that you put in the soil next to a plant. If you think the soil is too dry, you can control an automatic “watering can” from your smartphone.
Letzte Aktualisierung am 2021-01-09 / Affiliate Links / Bilder von der Amazon Product Advertising API