Loading...
OUR BLOG

Kawal LED menggunakan Telegram Bot dan NodeMCU ESP8266

Hi korang!

 

Tutorial blog kali ini kita akan belajar macam mana mengawal 2 LED iaitu RGB LED dan LED pada board NodeMCU melalui bot Telegram dengan menggunakan Arduino IDE. Untuk menghantar dan menerima data dengan aplikasi telegram kita akan menggunakan board NodeMCU ESP8266. LED akan ON dan OFF dengan menghantar mesej untuk memberi arahan daripada bot Telegram ke NodeMCU ESP8266 .

 

 

1. Install Telegram

 

Install aplikasi Telegram pada telefon atau laptop dan Sign Up atau Sign In ke akaun anda.

 

 

 

2. Create Telegram bot

 

 

Buat carian “botfather” dan klik seperti yang ditunjukkan di bawah. 

 

 

Kemudian, klik pada Start untuk memulakan bot dan keluar banyak pilihan pada menu.

 

 

Taip /newbot dan hantar mesej pada bot atau klik pada /newbot untuk membuat bot baharu yang akan digunakan dalam projek nanti. 

 

 

Kemudian, bot akan meminta anda memberikan nama dan username untuk bot yang nak dibuat. Sila guna unik username dan letakkan _bot atau bot dihujung untuk proses seterusnya. Selepas itu, anda akan mendapat token yang perlu anda copy dan paste id itu ke dalam code. Gunakan link yang diberikan dalam mesej untuk membuka bot anda.

 

 

 

4. Install ESP8266 Board ke dalam Arduino IDE

 

Jika anda belum pernah install ESP8266 board , anda boleh rujuk tutorial kami sebelum ini https://app.bdxtronix.com/blog/cara-install-board-nodemcu-pada-arduino-ide 

 

 

5. Download Universal Telegram Bot Library

 

Jika anda belum pernah menggunakan Telegram bot, rujuk link ini untuk download library. https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot

 

Kemudian, pergi ke Sketch > Include Library > Add.ZIP Library.

 

Cari library yang anda telah download tadi dan tambahkan ke dalam Arduino IDE anda.

 

 

6. Komponen yang diperlukan 

 

 

 

 

7. Litar

RGB LED 

 

LED 

 

8. Code

#include <ESP8266WiFi.h>

#include <WiFiClientSecure.h>

#include <UniversalTelegramBot.h>


#define WIFI_SSID "Nama Wifi Anda" //Masukkan nama wifi anda

#define WIFI_PASSWORD "Password Wifi Anda" //Masukkan wifi password anda

#define BOT_TOKEN "Bot token anda" //Telegram BOT Token (Dapat melalui Botfather)


const unsigned long BOT_MTBS = 1000; // BOT_MTBS check mesej baru setiap saat (1000miliseconds).


X509List cert(TELEGRAM_CERTIFICATE_ROOT);

//Create Wifi client 

WiFiClientSecure secured_client;

//Create bot dengan token dan client 

UniversalTelegramBot bot(BOT_TOKEN, secured_client);

unsigned long bot_lasttime; // last time messages' scan has been done


//define output

const int yellowledPin = 15;

int yellowledStatus = 0;

const int redledPin = 5;

int redledStatus = 0;

const int greenledPin = 4;

int greenledStatus = 0;

const int blueledPin = 2;

int blueledStatus = 0;


void handleNewMessages(int numNewMessages) //handleNewMessages function akan kawal mesej baru

{

  Serial.print("handleNewMessages ");

  Serial.println(numNewMessages);


 for (int i = 0; i < numNewMessages; i++)

  {

    String chat_id = 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 == "/yellowledon")

    {

      digitalWrite(yellowledPin, HIGH); // turn the yellow LED on 

      yellowledStatus = 1;

      bot.sendMessage(chat_id, "Yellow Led is ON", "");

    }

    if (text == "/yellowledoff")

    {

      yellowledStatus = 0;

      digitalWrite(yellowledPin, LOW); // turn the yellow LED off 

      bot.sendMessage(chat_id, "Yellow Led is OFF", "");

    }

    

   if (text == "/redledon")

    {

      digitalWrite(redledPin, HIGH); // turn the red LED on 

      redledStatus = 1;

      bot.sendMessage(chat_id, "Red Led is ON", "");

    }


    if (text == "/redledoff")

    {

      redledStatus = 0;

      digitalWrite(redledPin, LOW); // turn the red LED off 

      bot.sendMessage(chat_id, "Red Led is OFF", "");

    }

    

   if (text == "/greenledon")

    {

      digitalWrite(greenledPin, HIGH); // turn the green LED on 

      greenledStatus = 1;

      bot.sendMessage(chat_id, "Green Led is ON", "");

    }


    if (text == "/greenledoff")

    {

      greenledStatus = 0;

      digitalWrite(greenledPin, LOW); // turn the green LED off 

      bot.sendMessage(chat_id, "Green Led is OFF", "");

    }

    

    if (text == "/blueledon")

    {

      digitalWrite(blueledPin, HIGH); // turn the blue LED on 

      blueledStatus = 1;

      bot.sendMessage(chat_id, "Blue Led is ON", "");

    }


    if (text == "/blueledoff")

    {

      blueledStatus = 0;

      digitalWrite(blueledPin, LOW); // turn the blueLED off 

      bot.sendMessage(chat_id, "Blue Led is OFF", "");

    }



    if (text == "/yellowstatus")

    {

      if (yellowledStatus)

      {

        bot.sendMessage(chat_id, "Yellow Led is ON", "");

      }

      else

      {

        bot.sendMessage(chat_id, "Yellow Led is OFF", "");

      }

    }


    

    if (text == "/redstatus")

    {

      if (redledStatus)

      {

        bot.sendMessage(chat_id, "Red Led is ON", "");

      }

      else

      {

        bot.sendMessage(chat_id, "Red Led is OFF", "");

      }

    }


    

    if (text == "/greenstatus")

    {

      if (greenledStatus)

      {

        bot.sendMessage(chat_id, "Green Led is ON", "");

      }

      else

      {

        bot.sendMessage(chat_id, "Green Led is OFF", "");

      }

    }


    

    if (text == "/bluestatus")

    {

      if (blueledStatus)

      {

        bot.sendMessage(chat_id, "Blue Led is ON", "");

      }

      else

      {

        bot.sendMessage(chat_id, "Blue Led is OFF", "");

      }

    }


    if (text == "/start")

    {

      String welcome = "Selamat Datang, " + from_name + ".\n";

      welcome += "/yellowledon : to switch the Led ON\n";

      welcome += "/yellowledoff : to switch the Led OFF\n";

      welcome += "/redledon : to switch the Led ON\n";

      welcome += "/redledoff : to switch the Led OFF\n";

      welcome += "/greenledon : to switch the Led ON\n";

      welcome += "/greenledoff : to switch the Led OFF\n";

      welcome += "/blueledon : to switch the Led ON\n";

      welcome += "/blueledoff : to switch the Led OFF\n";

      welcome += "/yellowstatus : Returns current status of LED\n";

      welcome += "/redstatus : Returns current status of LED\n";

      welcome += "/greenstatus : Returns current status of LED\n";

      welcome += "/bluestatus : Returns current status of LED\n";

      bot.sendMessage(chat_id, welcome, "Markdown");

    }

  }

}



void setup()

{

  Serial.begin(115200); //iniatilize the serial monitor

  Serial.println();


  pinMode(yellowledPin, OUTPUT); // initialize digital ledPin as an output.

  delay(10);

  digitalWrite(yellowledPin, LOW); // initialize pin as off (active HIGH)

  pinMode(redledPin, OUTPUT); // initialize digital ledPin as an output.

  delay(10);

  digitalWrite(redledPin, LOW); // initialize pin as off (active HIGH)

  pinMode(greenledPin, OUTPUT); // initialize digital ledPin as an output.

  delay(10);

  digitalWrite(greenledPin, LOW); // initialize pin as off (active HIGH)

  pinMode(blueledPin, OUTPUT); // initialize digital ledPin as an output.

  delay(10);

  digitalWrite(blueledPin, LOW); // initialize pin as off (active HIGH)



 //board connect pada wifi 

  configTime(0, 0, "pool.ntp.org");      // get UTC time via NTP

  secured_client.setTrustAnchors(&cert); // Tambah root certificate untuk api.telegram.org

  Serial.print("Connecting to Wifi SSID "); //display WIFI SSID pada serial monitor

  Serial.print(WIFI_SSID);

 WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) 

  {

    Serial.print(".");

    delay(500);

  }

  Serial.print("\nWiFi connected. IP address: ");

  Serial.println(WiFi.localIP());


}

 

//check mesej baru setiap saat

void loop()  

{

  if (millis() - bot_lasttime > BOT_MTBS)

  {

    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

 

    while (numNewMessages)

    {

      Serial.println("got response"); //display pada Serial Monitor

      handleNewMessages(numNewMessages); 

      numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    }


    bot_lasttime = millis();

  }

}

 

Peringatan

 

Sila masukkan wifi ssid dan password wifi anda dan bot token telegram ke dalam code Arduino IDE sebelum anda upload. 

 

 

 

9. Output 

 

 

Tekan /start untuk mulakan telegram bot

 

 

Jika taip /redledon, red LED akan menyala. Jika taip /yellowledon, yellow LED akan menyala.

 

 

Jika taip /yellowledstatus, bot menghantar status yellow LED sedang menyala. Jika taip /greenledstatus, bot menghantar status green LED tidak menyala. 

 

 

Output pada Serial Monitor apabila user menghantar mesej baru. 

 

 

 

 

 

Jika anda suka dengan perkongsian tutorial dalam blog kami ni, jangan lupa untuk follow Facebook dan Instagram kami, kat situ ada bermacam info dan update terkini yang akan kami kongsikan kepada anda. Itu sahaja untuk tutorial kami. Stay update dan selamat mencuba!

 

 

 

 

 

Unsure Whether You Need Our Help?

Have you got an awesome new idea or project that you want to talk about? We're here to talk you through it. Flick us an email or give us a call to get started.