2025年5月20日 星期二

ESP32 DHT22 + Telegram 加入 /status 指令回傳目前溫濕度

ESP32 DHT22 + Telegram   

加入 /status 指令回傳目前溫濕度





//僅當溫濕度有變化時才傳送至 Telegram
//加入 /status 指令回傳目前溫濕度
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <DHT.h>

// WiFi 資訊
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Telegram Bot 資訊
// Initialize Telegram BOT
#define BOT_TOKEN "8023906815:AAE0KApbm5Ng00VCvO57JWA_XKtbx6a4IXM"  
// your Bot Token (Get from Botfather)
// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "7965218469"

// DHT 感測器設定
#define DHTPIN 15         // GPIO15 可更換
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// Telegram 通訊
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);

// 發送時間控制
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 3000; // 3 秒

// 新增儲存上一筆數據的變數
float lastTemp = NAN;
float lastHum = NAN;
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

//===========================================================
void setup() {
  Serial.begin(115200);
  dht.begin();

  // 連接 WiFi
  WiFi.begin(ssid, password);
  Serial.print("連線中");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi 已連線");

  // 啟用不安全連線(略過 SSL 憑證驗證)
  secured_client.setInsecure();

  // 初始訊息
  bot.sendMessage(CHAT_ID, "ESP32 啟動完成,開始回報溫濕度。", "");
}
//===========================================================
void loop() {
  // 處理指令
  if (millis() - lastTimeBotRan > botRequestDelay) {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    while (numNewMessages) {
      for (int i = 0; i < numNewMessages; i++) {
        String text = bot.messages[i].text;
        String chat_id = bot.messages[i].chat_id;

        if (text == "/status") {
          float t = dht.readTemperature();
          float h = dht.readHumidity();

          if (isnan(t) || isnan(h)) {
            bot.sendMessage(chat_id, "讀取感測器失敗", "");
          } else {
            String msg = "目前環境數據:\n";
            msg += "溫度:" + String(t, 1) + " °C\n";
            msg += "濕度:" + String(h, 1) + " %";
            bot.sendMessage(chat_id, msg, "");
          }
        }
      }
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    lastTimeBotRan = millis();
  }

  // 可搭配定時更新或僅處理指令
}
//===========================================================

沒有留言:

張貼留言

ESP32 (ESP-IDF in VS Code) MFRC522 + MQTT + PYTHON TKinter +SQLite

 ESP32 (ESP-IDF in VS Code) MFRC522 + MQTT + PYTHON TKinter +SQLite  ESP32 VS Code 程式 ; PlatformIO Project Configuration File ; ;   Build op...