Building and controlling a smart connected Home using Telegram and NodeMCU ESP32 .

Required Components :

Requests ESP32 NodeMCU temperature and humidity readings using the Telegram app :

Get Your Telegram User ID :

Preparing Arduino IDE:

BME280 Sensor Libraries

circuit diagram :

Code (C++):

#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)

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
client.setInsecure();
#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);
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();
}
}

How the Code Works:

#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

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Telegram User ID

#define CHAT_ID "XXXXXXXXXX"

Telegram Bot Token

#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  // your Bot Token (Get from Botfather)
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

BME280 Object

Adafruit_BME280 bme;

getReadings()

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;
}

handleNewMessages()

void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
for (int i=0; i<numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
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, "");
}
bool sendMessage(String chat_id, String text, String parse_mode = "")
bot.sendMessage(chat_id, welcome, "");
if (text == "/readings") {
String readings = getReadings();
bot.sendMessage(chat_id, readings, "");
}

setup()

Serial.begin(115200);
#ifdef ESP8266
client.setInsecure();
#endif

Init BME280

if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}

Init Wi-Fi

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}

loop()

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();
}
}
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}

Demonstration :

Control Outputs using Telegram — ESP32 :

#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>
// 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);
// Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
const int ledPin = 2;
bool ledState = LOW;
// 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 commands to control your outputs.\n\n";
welcome += "/led_on to turn GPIO ON \n";
welcome += "/led_off to turn GPIO OFF \n";
welcome += "/state to request current GPIO state \n";
bot.sendMessage(chat_id, welcome, "");
}
if (text == "/led_on") {
bot.sendMessage(chat_id, "LED state set to ON", "");
ledState = HIGH;
digitalWrite(ledPin, ledState);
}

if (text == "/led_off") {
bot.sendMessage(chat_id, "LED state set to OFF", "");
ledState = LOW;
digitalWrite(ledPin, ledState);
}

if (text == "/state") {
if (digitalRead(ledPin)){
bot.sendMessage(chat_id, "LED is ON", "");
}
else{
bot.sendMessage(chat_id, "LED is OFF", "");
}
}
}
}
void setup() {
Serial.begin(115200);
#ifdef ESP8266
client.setInsecure();
#endif
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);

// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
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();
}
}

Demonstration :

Conclusion :

--

--

--

Embedded software engineer student .

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Swift Package Manager Basics

Accceing Files from GoogleColab

How to Retrieve Message, User, Server, and Channel IDs on Discord

Common Pitfalls to Avoid in Code Reviews

Customizing Contact Form 7 WordPress Plugin Guide

IOTA Meets Couchbase

C program to generate a multiplication table

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mohamed El Hlafi

Mohamed El Hlafi

Embedded software engineer student .

More from Medium

Banksters? Low-Income Customers are being Hammered with Overdraft Fees.

Democratising Sports in India

Fluid flow in food industry

For the Cricketers — Updates with love from CricHeroes