hendriawan

IOT-telegram-01-LEDonoff-with-universal-telegrambot

Aug 18th, 2024
453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 2.03 KB | Source Code | 0 0
  1. #include <WiFi.h>
  2. #include <WiFiClientSecure.h>
  3. #include <UniversalTelegramBot.h>
  4. #include <ArduinoJson.h>
  5.  
  6. // SSID dan Password WiFi
  7. const char* ssid = "Wokwi-GUEST";
  8. const char* password = "";
  9.  
  10. // Telegram BOT
  11. #define BOTtoken "7111827908:AAFHy4wG3M26dLu9LmwElZYQiGwmQCvHDZs"
  12. #define CHAT_ID "11933555"
  13.  
  14. #define pin_led   23  // Pin untuk LED
  15.  
  16.  
  17. WiFiClientSecure client;
  18. UniversalTelegramBot bot(BOTtoken, client);
  19.  
  20. // Cek Pesan Setiap 1 detik
  21. int interval = 1000;
  22. unsigned long waktu_terakhir;
  23.  
  24. void setup() {
  25.   // Atur mode pin menjadi output
  26.   pinMode(pin_led, OUTPUT);
  27.  
  28.   // Serial monitor
  29.   Serial.begin(115200);
  30.  
  31.   // Hubungkan ke Wi-Fi
  32.   WiFi.mode(WIFI_STA);
  33.   WiFi.begin(ssid, password);
  34.   client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
  35.  
  36.   while (WiFi.status() != WL_CONNECTED) {
  37.     delay(1000);
  38.     Serial.println("Sedang menghubungkan ke WiFi..");
  39.   }
  40.  
  41.   // Tampilkan IP Address
  42.   Serial.println(WiFi.localIP());
  43. }
  44.  
  45. void loop() {
  46.   cek_pesan();
  47. }
  48.  
  49. // Cek Pesan Terbaru
  50. void cek_pesan() {
  51.   if (millis() > waktu_terakhir + interval) {
  52.     int banyakPesan = bot.getUpdates(bot.last_message_received + 1);
  53.  
  54.     while (banyakPesan) {
  55.       handleNewMessages(banyakPesan);
  56.       banyakPesan = bot.getUpdates(bot.last_message_received + 1);
  57.     }
  58.     waktu_terakhir = millis();
  59.   }
  60. }
  61.  
  62. // Memproses pesan yang diterima
  63. void handleNewMessages(int numNewMessages) {
  64.   for (int i = 0; i < numNewMessages; i++) {
  65.    
  66.     // Cek Chat ID
  67.     String chat_id = String(bot.messages[i].chat_id);
  68.     if (chat_id != CHAT_ID) {
  69.       bot.sendMessage(chat_id, "Unauthorized user", "");
  70.       continue;
  71.     }
  72.    
  73.     // Terima pesan dari telegram
  74.     String text = bot.messages[i].text;
  75.     Serial.println(text);
  76.  
  77.     if (text == "/led1on") {
  78.       bot.sendMessage(chat_id, "LED ON", "");
  79.       digitalWrite(pin_led, HIGH);  // Nyalakan LED
  80.     }
  81.    
  82.     if (text == "/led1off") {
  83.       bot.sendMessage(chat_id, "LED OFF", "");
  84.       digitalWrite(pin_led, LOW);  // Matikan LED
  85.     }
  86.   }
  87. }
  88.  
Advertisement