• nithya7rns

Controlling Esp8266 GPIO Pins using Telegram App

Updated: Dec 31, 2020


NodeMCU connected to LED

NodeMCU is a #WiFi module that allows us to connect to a network to transfer or exchange information online. It embeds an Esp8266 chip in it which is a WiFi microchip. Also, using messenger apps, the BOTs can be used for controlling a device.


In this article, we will explore how to connect the WiFi chip to a network and control the switching ON and OFF of an LED using the Telegram App. The control of LED is going to be done using the Arduino IDE.


Hardware List


The following components are used for building the circuit.


  1. NodeMCU

NodeMCU Module

NodeMCU is a platform provided for #IoT. It basically includes firmware (computer software that contains instructions and controls the hardware) which runs on Esp8266 WiFi SoC (software on-chip). It is open-source firmware available for prototyping and developing kits. MCU means a Micro-Controller Unit. The device contains GPIO (General Purpose Input Output) pins which send and receives data on connection to other devices.


Esp12e module is also an SoC used for WiFi and is used in this project.


The specifications of the Esp12e module are:

  • 32-bit lx106 RISC Microprocessor.

  • 80MHz-160MHz, the adjustable clock frequency.

  • Supports Arctic OS(Operating System).

  • 1 KB Internal #RAM.

  • 4 MB External flash.

  • 2.5V to 3.6V, 3.3V onboard.

  • 600 milliAmp Regulator.

  • 80 milliAmp Operating Current.

  • 20 microAmp Current in sleeping Mode.

  • 17 GPIO pins (which include ADC channels, 2 UART Interfaces, 4 PWM outputs, LED, Reset button, etc.).

Buy NodeMCU from here.


2. LED


LED

Light Emitting Diode is a commonly used light source. It is a semiconductor that emits light when current flows through it.


Buy LED from here.


3. Breadboard


Breadboard

The breadboard is the basic component of any circuit building process. All components, be it input sensors or output display devices are connected to the #Arduino or any other microcontroller using wired connections through a breadboard. The holes in the breadboard are in series. There are various sizes like full-sized, half-sized, and mini breadboards.


Buy Breadboard from here.


Circuit Diagram


The circuit diagram below shows the necessary connections of the NodeMCU device and LED through the breadboard.


Circuit Connections

The circuit connections for setting up this device is simple. The LED is connected to the breadboard. The positive(longer) #terminal of the LED is connected to GPIO pin 5 and the negative(shorter) terminal of the LED is connected to the GND(Ground) pin of the NodeMCU through the breadboard.


The NodeMCU is then interfaced with the Arduino IDE.


For reference, the Pin diagram of NodeMCU is shown below.

NodeMCU Pin Diagram

Code:


The following code needs to be entered into the Arduino IDE and injected into the NodeMCU WiFi chip.


#include <ESP8266WiFi.h>

#include <WiFiClientSecure.h>

#include <UniversalTelegramBot.h>

These are the first lines of code which include the header files required for the program to execute properly. These header files are the additional ones which need to be selected from the library and installed. The detailed procedure is given in the video at the end of the article.

char ssid[] = "XXXXXXXXX";
char password[] = "XXXXXXX";

The next step is to get the device connected to the internet. The network must be set by giving the id (username) of the network and the password which will be initialized to the character variables "ssid" and "password" respectively as declared in the code.

#define BOTtoken "1327XXXXXXXX:AAGUqjhXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

This line of code does the function of initializing and connecting to the Telegram BOT. Every BOT will have a unique token or number assigned to it through which we can access and control it. This token can be obtained from the Telegram app (#BOTfather), the steps for which are explained in the video.

WiFiClientSecure client;

As seen above, we have included the header file "WiFiClientSecure.h". Now we will be declaring an object for the same, namely "client".

UniversalTelegramBot bot(BOTtoken, client);

Also, we have included the header file "UniversalTelegramBot.h" under which we are going to use a functioning bot( ) which will take BOTtoken and client, a defined variable, and an object as its parameters. This is an inbuilt function.

int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

Here we give a delay of one second, that is, the messages will be checked every one second. We declare a variable to hold a huge value for time, under the name "lastTimeBotRan".

const int ledPin = 5;
int ledStatus = 0;

As we have connected the positive terminal of the LED to the GPIO pin 5, we initialize a constant value for ledPin as 5. Another variable ledStatus is set to 0.

void handleNewMessages(int numNewMessages) {
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));

Next, a function "handleNewMessages" starts its execution. It takes the value of numNewMessages as its parameter which is the count of the number of messages that have been received. Two statements are printed on the Serial monitor. The first statement prints the number of new messages and the next prints the New messages itself.

for (int i=0; i<numNewMessages; i++) {
    String chat_id = String(bot.messages[i].chat_id);
    String text = bot.messages[i].text;

A for loop is written which takes in the chat_id and the text of each new message received.

String from_name = bot.messages[i].from_name;
    if (from_name == "") from_name = "Guest";

Then, the sender of the message is noted. If the name is present as a saved name, the name is stored and if the name is not available, then the sender name is stored as Guest.

if (text == "/ledon") {
      digitalWrite(ledPin, HIGH);   
      ledStatus = 1;
      bot.sendMessage(chat_id, "Led is ON", "");
    }
if (text == "/ledoff") {
ledStatus = 0;
digitalWrite(ledPin, LOW);
bot.sendMessage(chat_id, "Led is OFF", "");
}

If the text sent through the message is "ledon", the LED is switched on using the function digitalWrite(ledPin, HIGH). The status is again set back to 1 and the message is sent to the BOT that the LED is ON (voltage is turned High).

The same process happens for the LED off function except the ledStatus is set to 0 when the LED is turned OFF and the same message is sent to the BOT.

if (text == "/status") {
      if(ledStatus){
        bot.sendMessage(chat_id, "Led is ON", "");
      } else {
        bot.sendMessage(chat_id, "Led is OFF", "");
      }
    }

If the user asks for the status of the LED, the above code does the function of checking the value of "ledStatus", whether the value is 1 or 0, and displays the message accordingly.

if (text == "/start") {
      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
      welcome += "This is Flash Led Bot example.\n\n";
      welcome += "/ledon : to switch the Led ON\n";
      welcome += "/ledoff : to switch the Led OFF\n";
      welcome += "/status : Returns current status of LED\n";
      bot.sendMessage(chat_id, welcome, "Markdown");
    }
  }
}

If the user sends for the message to start the process again, the values stored are reassigned to the basic values and the Welcome message is shown along with the basic statements that can be executed along with what process they carry out.

void setup() {
  Serial.begin(115200);

This is the setup( ) function where the Baudrate is set.

client.setInsecure();

This line of code is used for the secure transfer of data sent to the BOT.

WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

If the device was previously connected to a WiFi network, the above lines of code will disconnect it so that we can it to the desired network.

Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  pinMode(ledPin, OUTPUT);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  } 

The next step after disconnecting to the previous network is to connect to the desired network. The LED is set to Output mode and while the WiFi is still connecting a series of Dots are printed on the Serial Monitor with a delay of 0.5 seconds.

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

The status of the WiFi network is printed on the screen and the IP address is printed.

pinMode(ledPin, OUTPUT); 
  delay(10);
  digitalWrite(ledPin, LOW);

The pin mode is reassigned to Output and the LED is turned off (by assigning the value LOW).

void loop() {
  if (millis() > lastTimeBotRan + botRequestDelay)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

The loop( ) function in the program Is going to check the time taken for the #BOT functioning, which is to receive the messages and the delay occurred is added up, and based on the condition the values related to the BOT are updated.

while(numNewMessages) {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }

While the numNewMessages value is 1, the "got response" message is printed, and the following statements are executed which again update the related values.

lastTimeBotRan = millis();

The value for the variable "lastTimeBotRan" is equated to the function "millis( )" value which gives the time the Arduino board has been running the current program.


COMPLETE CODE

/*******************************************************************
    A telegram bot for your ESP8266 that controls the 
    onboard LED. The LED in this example is active low.

    Parts:
    D1 Mini ESP8266 * - http://s.click.aliexpress.com/e/uzFUnIe
    (or any ESP8266 board)

      = Affilate

    If you find what I do useful and would like to support me,
    please consider becoming a sponsor on Github
    https://github.com/sponsors/witnessmenow/


    Written by Brian Lough
    YouTube: https://www.youtube.com/brianlough
    Tindie: https://www.tindie.com/stores/brianlough/
    Twitter: https://twitter.com/witnessmenow
 *******************************************************************/

// The version of ESP8266 core needs to be 2.5 or higher
// or else your bot will not connect.

// ----------------------------
// Standard ESP8266 Libraries
// ----------------------------

#include <ESP8266WiFi.h>

#include <WiFiClientSecure.h>

// ----------------------------
// Additional Libraries - each one of these will need to be installed.
// ----------------------------

#include <UniversalTelegramBot.h>

// Initialize Wifi connection to the router
char ssid[] = "XXXXXXXXX";     // your network SSID (name)
char password[] = "XXXXXXX"; // your network key

// Initialize Telegram BOT
#define BOTtoken "1327XXXXXXXX:AAGUqjhXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // 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;

const int ledPin = 5;
int ledStatus = 0;

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);
    String text = bot.messages[i].text;

    String from_name = bot.messages[i].from_name;
    if (from_name == "") from_name = "Guest";

    if (text == "/ledon") {
      digitalWrite(ledPin, HIGH);   // turn the LED on (HIGH is the voltage level)
      ledStatus = 1;
      bot.sendMessage(chat_id, "Led is ON", "");
    }

    if (text == "/ledoff") {
      ledStatus = 0;
      digitalWrite(ledPin, LOW);    // turn the LED off (LOW is the voltage level)
      bot.sendMessage(chat_id, "Led is OFF", "");
    }

    if (text == "/status") {
      if(ledStatus){
        bot.sendMessage(chat_id, "Led is ON", "");
      } else {
        bot.sendMessage(chat_id, "Led is OFF", "");
      }
    }

    if (text == "/start") {
      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
      welcome += "This is Flash Led Bot example.\n\n";
      welcome += "/ledon : to switch the Led ON\n";
      welcome += "/ledoff : to switch the Led OFF\n";
      welcome += "/status : Returns current status of LED\n";
      bot.sendMessage(chat_id, welcome, "Markdown");
    }
  }
}


void setup() {
  Serial.begin(115200);

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

  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  pinMode(ledPin, OUTPUT);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

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

  pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
  delay(10);
  digitalWrite(ledPin, LOW); // initialize pin as off (active high)
}

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

code
.txt
Download TXT • 4KB

Note: Please change the file format to .ino(Arduino IDE) format before you upload the code to the #ESP8266 board.


Working:


The working of this circuit can be categorized as connecting, interfacing, and controlling.


The connecting part is when the circuit connections are done, the BOT is set up in the #Telegram App, a unique BOT name, id, etc are assigned. The same is reflected in the code used.


The interfacing part is where the BOT name and the device are synchronized, the device is connected to the desired network and the connection is established.


The controlling part is totally user-defined. Once the connection is established, statements can be executed by sending messages through Telegram BOT to start, turn ON, turn OFF, and know the status of the LED. The statements and their syntax is defined in the code and also shown in the video given below.


Video By - Abhishek Goud


This article deals with the setting of the BOT in Telegram, #interfacing the device, and controlling the LED. The program has a wider scope wherein different devices can be interfaced with the BOT and made user friendly. For instance, the circuit designed for a parking lot can be interfaced with the BOT to note down the number of vehicles entering and leaving the place. There are many applications and a huge scope of development of this project, especially in everyday life.


SEE ALSO:

  • Facebook
  • YouTube
  • Instagram
  • LinkedIn
LearnElectronics
Contact Us
© Copyright - LearnElectronics 2020.