2026年2月21日 星期六

ESP32 Telegram Chat Action(聊天狀態) 的功能

ESP32 Telegram   Chat Action(聊天狀態) 的功能



//*******************************************************************/
/*******************************************************************
*  An example of bot that echos back any messages received,
*  including ones from channels
*                                                                          
*  written by Brian Lough
*******************************************************************/
#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
bool Start = false;

void handleNewMessages(int numNewMessages)
{
  Serial.println("handleNewMessages");
  Serial.println(String(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 == "/send_test_action")
    {
      bot.sendChatAction(chat_id, "typing");
      delay(4000);
      bot.sendMessage(chat_id, "Did you see the action message?");

      // You can't use own message, just choose from one of bellow

      //typing for text messages
      //upload_photo for photos
      //record_video or upload_video for videos
      //record_audio or upload_audio for audio files
      //upload_document for general files
      //find_location for location data

      //more info here - https://core.telegram.org/bots/api#sendchataction
    }

    if (text == "/start")
    {
      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
      welcome += "This is Chat Action Bot example.\n\n";
      welcome += "/send_test_action : to send test chat action message\n";
      bot.sendMessage(chat_id, welcome);
    }
  }
}

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

  // 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 機器人範例,主要展示了 Chat Action(聊天狀態) 的功能(例如:顯示「對方正在輸入中...」)。

以下為您逐行解說:


1. 引入庫與基本參數設定

C++
#include <WiFi.h>              // ESP32 WiFi 連線庫
#include <WiFiClientSecure.h>  // HTTPS 加密傳輸庫(Telegram 規定使用)
#include <UniversalTelegramBot.h> // Telegram Bot 核心庫
  • WIFI_SSID: 設定為 Wokwi-GUEST,這是為了在 Wokwi 線上模擬器執行的設定。

  • BOT_TOKEN: 機器人的身份證,用來連接 Telegram 伺服器。

  • BOT_MTBS: 每隔 1000 毫秒(1秒)檢查一次新訊息,避免頻繁請求導致被伺服器封鎖。


2. 核心處理邏輯:handleNewMessages

當機器人收到訊息時,會進入這個函式處理:

C++
void handleNewMessages(int numNewMessages) {
  for (int i = 0; i < numNewMessages; i++) {
    String chat_id = bot.messages[i].chat_id; // 取得發送者的 ID
    String text = bot.messages[i].text;       // 取得訊息內容
    String from_name = bot.messages[i].from_name; // 取得發送者暱稱
    if (from_name == "") from_name = "Guest";   // 如果沒暱稱則顯示 Guest

    // --- 測試聊天動作功能 ---
    if (text == "/send_test_action") {
      bot.sendChatAction(chat_id, "typing"); // 在手機端顯示「機器人正在輸入中...」
      delay(4000); // 模擬處理過程,停 4 秒
      bot.sendMessage(chat_id, "Did you see the action message?"); // 發送正式訊息
    }

    // --- 起始畫面 ---
    if (text == "/start") {
      String welcome = "Welcome..., " + from_name + ".\n";
      welcome += "/send_test_action : to send test chat action message\n";
      bot.sendMessage(chat_id, welcome); // 傳送歡迎詞與指令列表
    }
  }
}

小知識:sendChatAction 可以提升使用者體驗,讓使用者知道機器人正在處理(如:typing 正在輸入、upload_photo 正在上傳圖片)。


3. 初始化設定:setup

這部分只在開發板啟動時執行一次。

C++
void setup() {
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // 連接 WiFi
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // 設定安全憑證

  while (WiFi.status() != WL_CONNECTED) { delay(500); } // 等待網路連線

  // 重要:取得正確的網路時間
  configTime(0, 0, "pool.ntp.org"); 
  time_t now = time(nullptr);
  while (now < 24 * 3600) { // 如果時間不正確,HTTPS 連線會失效
    delay(100);
    now = time(nullptr);
  }
}

4. 主迴圈:loop

程式會在這裡不斷循環運行。

C++
void loop() {
  // 檢查是否超過了設定的檢查間隔 (1秒)
  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(); // 更新計時器
  }
}

總結

這段程式碼比一般的 Echo Bot 多了:

  1. 使用者辨識:會抓取 from_name(使用者姓名)。

  2. 指令觸發:使用了 if (text == "/start") 這種結構來製作選單。

  3. 互動感:利用 sendChatAction 讓機器人看起來像「真人」在打字,這在處理耗時任務(如感測器讀取或圖片生成)時非常有用。

ESP32 Telegram Channel POST

 ESP32 Telegram Channel POST

這段程式碼是一個基於 ESP32的 Telegram 機器人範例,功能非常單純: 它會接收使用者傳送的訊息,並原封不動地回傳(Echo)。



//*******************************************************************/
/*******************************************************************
*  An example of bot that echos back any messages received,
*  including ones from channels
*                                                                          
*  written by Brian Lough
*******************************************************************/
#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 "77389402154:AAHbrWu9ovb1BKPQ2yWs1bNSjNxfCGCrEWU-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

void handleNewMessages(int numNewMessages)
{
  for (int i = 0; i < numNewMessages; i++)
  {
    if (bot.messages[i].type == "channel_post")
    {
      bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].chat_title + " " + bot.messages[i].text, "");
    }
    else
    {
      bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
    }
  }
}

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

  // 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, "tock.stdtime.gov.tw"); // get UTC time via tock.stdtime.gov.tw
  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();
  }
}


程式碼逐行詳解

1. 引用與基本定義

C++
#include <WiFi.h>              // 用於處理 ESP32 的 WiFi 連線
#include <WiFiClientSecure.h>  // 用於處理 HTTPS 加密連線(Telegram 要求 SSL/TLS)
#include <UniversalTelegramBot.h> // Telegram Bot 的核心 API 函式庫

2. 設定網路與機器人資訊

C++
#define WIFI_SSID "Wokwi-GUEST"      // WiFi 帳號(這裡使用 Wokwi 模擬器的預設值)
#define WIFI_PASSWORD ""             // WiFi 密碼
#define BOT_TOKEN "7738940254:..."   // 從 BotFather 取得的機器人唯一金鑰
const unsigned long BOT_MTBS = 1000; // 設定掃描新訊息的間隔時間(1000 毫秒 = 1 秒)

3. 實例化物件

C++
WiFiClientSecure secured_client;             // 建立加密的網路連線用戶端
UniversalTelegramBot bot(BOT_TOKEN, secured_client); // 建立機器人物件
unsigned long bot_lasttime;                  // 記錄上次檢查訊息的時間

4. 處理新訊息的函式 (handleNewMessages)

這是機器人的「大腦」,決定收到訊息後要做什麼。

C++
void handleNewMessages(int numNewMessages) {
  for (int i = 0; i < numNewMessages; i++) { // 逐一處理收到的每一則訊息
    // 如果訊息來自「頻道 (Channel)」
    if (bot.messages[i].type == "channel_post") {
      // 回傳:頻道名稱 + 訊息內容
      bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].chat_title + " " + bot.messages[i].text, "");
    } 
    // 如果是個人私訊或群組訊息
    else {
      // 回傳:原本的訊息內容
      bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
    }
  }
}

5. 初始化設定 (setup)

C++
void setup() {
  Serial.begin(115200); // 開啟序列號視窗,波特率 115200

  // 1. 連接 WiFi
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  // 加入 Telegram 的根憑證,確保 HTTPS 連線安全性
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); 
  
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("\nWiFi connected.");

  // 2. 同步網路時間(Telegram API 需要正確的時間戳記才能運作)
  configTime(0, 0, "tock.stdtime.gov.tw"); 
  time_t now = time(nullptr);
  while (now < 24 * 3600) { // 等待時間同步完成
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);
}

6. 主要迴圈 (loop)

C++
void loop() {
  // 檢查是否到了該掃描訊息的時間 (每秒一次)
  if (millis() - bot_lasttime > BOT_MTBS) {
    // 向 Telegram 伺服器詢問是否有新訊息,並回報最後收到的 ID
    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(); // 更新檢查時間
  }
}

重要提醒

  1. 安全性:你在程式碼中直接寫出了 BOT_TOKEN。雖然這在測試時很方便,但如果上傳到 GitHub 等公開平台,別人就能控制你的機器人。請妥善保管此 Token。

  2. 根憑證:TELEGRAM_CERTIFICATE_ROOT 是 UniversalTelegramBot 內建的憑證。如果 Telegram 更新了憑證而你的庫太舊,連線可能會失敗。

  3. Wokwi 模擬:這段程式碼可以直接在 Wokwi 平台上運行,因為它使用了模擬器專用的 WiFi SSID。

2026年2月16日 星期一

DISCORD ESP32

DISCORD  ESP32 


 

    準備工作:取得 Discord Webhook URL

  1. 開啟 Discord 並進入你的伺服器。

  2. 進入頻道設定(齒輪圖示) > 整合 (Integrations) > Webhook。

  3. 點擊「建立 Webhook」,設定好名字後點擊 「複製 Webhook URL」。





main.ino

#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h> // 必須包含此庫以處理 HTTPS
#include <ArduinoJson.h>
#include <DHT.h>

// --- Discord Webhook 設定 ---
// 請務必確認此 URL 正確且包含 ID 與 Token
const char* DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/1472888818762907763/SpUB8clIuuvq54_ZCtEDaYaVRiDSPQJNIiX80JbWleFP8fUA79WqnXnJEeSBDC4-yfVk";

// --- Wokwi 模擬 Wi-Fi 憑證 ---
const char* WIFI_SSID     = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";

// --- 硬體腳位定義 ---
#define DHTPIN 15
#define DHTTYPE DHT22
#define LED_PIN 2
DHT dht(DHTPIN, DHTTYPE);

/**
 * @brief 向 Discord 發送訊息 (支援 HTTPS)
 */
void sendDiscordMessage(String content) {
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("WiFi 未連線,無法發送訊息");
        return;
    }

    WiFiClientSecure *client = new WiFiClientSecure;
    if(client) {
        // 重要:在 Wokwi 中必須跳過 SSL 憑證檢查
        client->setInsecure();

        HTTPClient http;
        Serial.print("\n[HTTP] 開始發送至 Discord...");
       
        if (http.begin(*client, DISCORD_WEBHOOK_URL)) {
            http.addHeader("Content-Type", "application/json");

            StaticJsonDocument<512> doc;
            doc["content"] = content;

            String requestBody;
            serializeJson(doc, requestBody);
           
            int httpResponseCode = http.POST(requestBody);
           
            if (httpResponseCode > 0) {
                Serial.printf(" 狀態碼: %d\n", httpResponseCode);
                if (httpResponseCode == 204) {
                    Serial.println("✅ Discord 訊息發送成功!");
                } else if (httpResponseCode == 400) {
                    Serial.println("❌ 錯誤 400:請檢查 Webhook URL 或 JSON 格式");
                    Serial.println(http.getString()); // 印出 Discord 的錯誤訊息
                }
            } else {
                Serial.printf(" 失敗,錯誤原因: %s\n", http.errorToString(httpResponseCode).c_str());
            }
            http.end();
        } else {
            Serial.println("無法連接伺服器");
        }
        delete client; // 釋放記憶體
    }
}

void setup() {
    Serial.begin(115200);
    pinMode(LED_PIN, OUTPUT);
    dht.begin();

    // 啟動提示
    digitalWrite(LED_PIN, HIGH); delay(200);
    digitalWrite(LED_PIN, LOW);  delay(200);

    // 1. 連接 Wi-Fi
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("連線至 Wi-Fi...");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nWi-Fi 已連線! IP: " + WiFi.localIP().toString());

    // 2. 初始讀取數據並發送
    delay(2000); // 等待 DHT 穩定
    float h = dht.readHumidity();
    float t = dht.readTemperature();

    if (isnan(h) || isnan(t)) {
        Serial.println("DHT22 讀取失敗!");
        sendDiscordMessage("⚠️ **ESP32 警告**:無法讀取 DHT22 感測器數據!");
    } else {
        String report = "🚀 **ESP32 監控站啟動**\n🌡️ 溫度: `" + String(t, 1) + "°C`\n💧 濕度: `" + String(h, 1) + "%`";
        sendDiscordMessage(report);
       
        if (t > 30.0) digitalWrite(LED_PIN, HIGH);
    }
}
void loop() {
    static unsigned long lastUpdate = 0;
    // 將更新頻率稍微拉長到 60 秒,避免被 Discord 判定為惡意攻擊
    if (millis() - lastUpdate > 60000) {
        lastUpdate = millis();
       
        float t = dht.readTemperature();
        float h = dht.readHumidity();
       
        if (!isnan(t) && !isnan(h)) {
            // 先確認 WiFi 是否還在,不在就重連
            if (WiFi.status() != WL_CONNECTED) {
                WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
                return;
            }
           
            String msg = "🔄 定時回報 - 溫度: " + String(t, 1) + "°C, 濕度: " + String(h, 1) + "%";
            sendDiscordMessage(msg);
        }
    }
}

arduino_secrets.h

#define SECRET_SSID "Wokwi-GUEST"
#define SECRET_PASS ""
//Copy the webhook url here:
#define SECRET_WEBHOOK "https://discord.com/api/webhooks/1472888818762907763/SpUB8clIuuvq54_ZCtEDaYaVRiDSPQJNIiX80JbWleFP8fUA79WqnXnJEeSBDC4-yfVk"
#define SECRET_TTS "false"

discord.h

#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>

const char ssid[] = SECRET_SSID;    // Network SSID (name)
const char pass[] = SECRET_PASS;    // Network password (use for WPA, or use as key for WEP)
const String discord_webhook = SECRET_WEBHOOK;
const String discord_tts = SECRET_TTS;

WiFiMulti WiFiMulti;

void connectWIFI() {
  WiFiMulti.addAP(ssid, pass);
  WiFi.mode(WIFI_STA);
  Serial.print("[WiFi] Connecting to: ");
  Serial.println(ssid);
  // wait for WiFi connection
  while ((WiFiMulti.run() != WL_CONNECTED)) {
    Serial.print(".");
  }
  Serial.println("[WiFi] Connected");
}

void sendDiscord(String content) {
  WiFiClientSecure *client = new WiFiClientSecure;
  // WiFiClientSecure *client;

  if (client) {
    client->setInsecure(); // Disable SSL certificate verification
    {
      HTTPClient https;
      Serial.println("[HTTP] Connecting to Discord...");
      Serial.println("[HTTP] Message: " + content);
      Serial.println("[HTTP] TTS: " + discord_tts);
      if (https.begin(*client, discord_webhook)) {  // HTTPS
        // start connection and send HTTP header
        https.addHeader("Content-Type", "application/json");
        int httpCode = https.POST("{\"content\":\"" + content + "\",\"tts\":" + discord_tts +"}");

        // httpCode will be negative on error
        if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          Serial.print("[HTTP] Status code: ");
          Serial.println(httpCode);

          // file found at server
          if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            String payload = https.getString();
            Serial.print("[HTTP] Response: ");
            Serial.println(payload);
          }
        } else {
          Serial.print("[HTTP] Post... failed, error: ");
          Serial.println(https.errorToString(httpCode).c_str());
        }

        https.end();
      } else {
        Serial.printf("[HTTP] Unable to connect\n");
      }

      // End extra scoping block
    }

    delete client;
  } else {
    Serial.println("[HTTP] Unable to create client");
  }
}





import machine
import dht
import network
import time
import urequests as requests
import ujson
import os
import gc

# --- 設定區 ---
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""

# Discord Webhook 設定
DISCORD_ID = "1472888818762907763"
DISCORD_TOKEN = "SpUB8clIuuvq54_ZCtEDaYaVRiDSPQJNIiX80JbWleFP8fUA79WqnXnJEeSBDC4-yfVk"
URL = "https://discord.com/api/webhooks/{}/{}".format(DISCORD_ID, DISCORD_TOKEN)

# 硬體定義
led_pin = machine.Pin(2, machine.Pin.OUT)     # 你的 LED 腳位 (GPIO 2)
dht_sensor = dht.DHT22(machine.Pin(15))      # 你的 DHT22 腳位 (GPIO 15)
button_pin = machine.Pin(35, machine.Pin.IN, machine.Pin.PULL_UP) # 按鈕 (GPIO 35)

button_down = False

# --- 網路連線 ---
def connect_wifi():
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    if not wifi.isconnected():
        print('正在連線到 WiFi...')
        wifi.connect(WIFI_SSID, WIFI_PASS)
        while not wifi.isconnected():
            time.sleep(1)
            print('.', end='')
    return wifi

# --- 按鈕中斷處理 ---
def button_handler(pin):
    global button_down
    # 簡單去彈跳處理
    button_down = True

# 綁定中斷
button_pin.irq(trigger=machine.Pin.IRQ_FALLING, handler=button_handler)

# --- 發送 Discord 訊息 ---
def send_discord_message(content):
    connect_wifi()
    gc.collect() # 釋放記憶體,防止 SSL 連線記憶體不足
   
    # 修正重點:處理換行符號以符合 JSON 規範,避免 400 錯誤
    # Discord 的 JSON body 中,換行符號必須被轉義為 \\n
    json_content = content.replace('\n', '\\n')
    payload = '{"content": "' + json_content + '"}'
   
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        print("\n 訊息發送中...")
        # 設定 timeout 防止模擬器連線卡死
        response = requests.post(URL, data=payload.encode('utf-8'), headers=headers, timeout=10)
       
        print("Discord 回應狀態碼:", response.status_code)
       
        if response.status_code == 400:
            print("❌ 格式錯誤原因:", response.text)
        elif response.status_code == 204:
            print("✅ 訊息發送成功!")
           
        response.close()
    except Exception as e:
        print("❌ 網路發送異常 (可能是 SSL EOF):", e)
   
    gc.collect()

# --- 主程式 ---
if __name__ == '__main__':
    print("系統啟動: " + os.uname().sysname)
    led_pin.value(0)
   
    # 啟動時發送一次通知
    send_discord_message("🚀 ESP32 MicroPython 監控站已啟動!")

    while True:
        if button_down:
            print("\n偵測到按鈕按下,讀取數據中...")
            led_pin.value(1) # 處理時亮燈
           
            try:
                dht_sensor.measure()
                temp = dht_sensor.temperature()
                humi = dht_sensor.humidity()
               
                # 建立多行訊息
                msg = "📊 **環境監測數據**\n🌡️ 溫度: {:.1f}°C\n💧 濕度: {:.1f}%".format(temp, humi)
                print(msg)
               
                # 發送至 Discord
                send_discord_message(msg)
               
                # 簡易 LED 控制邏輯:溫度大於 30 度維持亮燈
                if temp <= 30:
                    led_pin.value(0)
                else:
                    print("⚠️ 溫度過高!")
                   
            except OSError as e:
                print("DHT22 讀取失敗:", e)
                send_discord_message("⚠️ 無法讀取感測器數據")
                led_pin.value(0)
           
            # 處理完畢,重置按鈕狀態
            button_down = False
           
        # 讓 CPU 休息一下
        time.sleep_ms(200)

MIFARE Classic Command Flow Diagram

MIFARE Classic Command Flow Diagram   這個程式將圖片中的 MIFARE Classic Command Flow Diagram 完整繪製在畫布上(包含中英文對照、虛線錯誤返回路徑、實線流程箭頭以及右側的「典型交易時間」資訊),並提供「上一...