2026年2月21日 星期六

ESP32 Telegram FlashLED

ESP32 Telegram FlashLED 


/*******************************************************************
    A telegram bot for your ESP32 that controls the
    onboard LED. The LED in this example is active low.
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "7738940254:AAHbrWu9ovb1BKPQyWsbNSjNxfCGCrEWU-o"

const unsigned long BOT_MTBS = 1000; // mean time between scan messages

WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime; // last time messages' scan has been done

const int ledPin = 2;
int ledStatus = 0;

void handleNewMessages(int numNewMessages)
{
  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 == "/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);
  Serial.println();

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

  // attempt to connect to Wifi network:
  Serial.print("Connecting to Wifi SSID ");
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Retrieving time: ");
  configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);
}

void loop()
{
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    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);
    }

    bot_lasttime = millis();
  }
}
程式碼是一個透過 Telegram 遠端控制 ESP32 硬體(LED 燈)的經典範例。

這段程式碼與前一版非常相似,但在 LED 電位邏輯上做了修改。這次的程式改為使用 HIGH 來開燈,LOW 來關燈(即 Active High 邏輯)。

以下是詳細的逐行解說:


1. 硬體定義與全域變數

C++
const int ledPin = 2;              // 定義 LED 接在 GPIO 2 (ESP32 內建 LED)
int ledStatus = 0;                 // 變數:記錄燈狀態 (0=關, 1=開)
const unsigned long BOT_MTBS = 1000; // 掃描新訊息的間隔 (1秒)

2. 核心處理函式:handleNewMessages

當機器人收到新訊息時,會進入此迴圈判斷指令:

  • 讀取資訊

    • chat_id: 誰傳來的(用來回傳訊息)。

    • text: 傳了什麼指令(如 /ledon)。

    • from_name: 使用者的稱呼。

  • 指令判斷

    • /ledon:執行 digitalWrite(ledPin, HIGH)。此時 GPIO 輸出 3.3V,點亮 LED。

    • /ledoff:執行 digitalWrite(ledPin, LOW)。輸出 0V,熄滅 LED。

    • /status:檢查 ledStatus 變數,並回傳目前的狀態文字。

    • /start:傳送歡迎訊息與「指令選單」清單。


3. 初始化設定:setup

這部分負責程式啟動時的硬體與網路準備:

C++
pinMode(ledPin, OUTPUT);    // 設定 GPIO 2 為輸出模式
digitalWrite(ledPin, LOW);  // 初始化:預設為關燈

WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // 啟動 WiFi 連線
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // 設定 Telegram 安全憑證

// 網路對時:Telegram API 必須確保時間正確才能建立加密連線
configTime(0, 0, "pool.ntp.org"); 

4. 主迴圈:loop

程式會不斷檢查是否有新訊息:

C++
if (millis() - bot_lasttime > BOT_MTBS) {
    // 取得新訊息數量
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while (numNewMessages) { 
        handleNewMessages(numNewMessages); // 處理訊息
        numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    bot_lasttime = millis(); // 更新檢查時間
}


沒有留言:

張貼留言

ESP32 Telegram 指令選單(Bot Commands)

ESP32 Telegram 指令選單(Bot Commands)  /*******************************************************************  ***********************************...