---
# System prepended metadata

title: ESP32使用MQTT物聯網通訊協定
tags: [已編輯]

---

# ESP32使用MQTT物聯網通訊協定
### 成果展示
![image](https://hackmd.io/_uploads/BkINh7KB1g.png)
![image](https://hackmd.io/_uploads/rJjFpXKSJg.png)

### ESP32-WROOM-32腳位圖
![image](https://hackmd.io/_uploads/SktJQlQHJl.png)

### 使用材料
1. ESP32-WROOM-32*1
2. 三色LED全彩模組*1
3. DHT11溫溼度感測器

### LED使用到的引腳

| 顏色 | 引腳 | 
| -------- | -------- | 
| 紅色     | GPIO15     | 
| 綠色     | GPIO2     | 
| 藍色     | GPIO4    | 
| 接地     | GND       | 

### DHT11使用到的引繳
| DHT11 | 引腳 | 
| -------- | -------- | 
| -       | GND       | 
| +       | VIN       | 
| OUT     | RX2(16)   | 

### 接線圖
![image](https://hackmd.io/_uploads/Hk8AOoXBJx.png)
![image](https://hackmd.io/_uploads/S1B1KoQS1l.png)

### 程式碼
```csharp=
#include <WiFi.h>          // 引入Wifi
#include <PubSubClient.h>  // 引入 PubSubClient使用 MQTT
#include <HTTPClient.h>
#include <DHT.h>
#define DHT11PIN 16
DHT dht(DHT11PIN, DHT11);
// WiFi 設定
const char* ssid = "KS_3F-3B_2.4G";         // WiFi SSID
const char* password = "12345678900000";   // WiFi密碼
// MQTT 設定
const char* mqtt_server = "34.81.46.57";  // MQTT 位置
const int mqtt_port = 1883;               // MQTT 埠號
const char* mqtt_user = "a79899569";      // MQTT帳號
const char* mqtt_pass = "a79899578";      // MQTT密碼
const char* serverName = "http://34.81.46.57/insert_data.php";  // 伺服器及插入資料庫php位置
WiFiClient espClient;            // WiFi
PubSubClient client(espClient);  // MQTT

// 連接至WiFi
void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to WiFi...");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
}
//連接到MQTT
void reconnect() {
  // 不斷嘗試連線
  while (!client.connected()) {
    Serial.print("Connecting to MQTT...");

    // 嘗試連接，傳入 ID、帳號和密碼
    if (client.connect("ESP32Client", mqtt_user, mqtt_pass)) {
      Serial.println("Connected to MQTT");
    } else {
      Serial.print("Failed, rc=");
      Serial.print(client.state());
      Serial.println(" Trying again in 5 seconds...");
      delay(5000);
    }
  }
}
const int redPin = 15;
const int greenPin = 2;
const int bluePin = 4;
float temp;
// 初始化
void setup() {
  Serial.begin(115200);
  dht.begin();
  // lcd設置
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  setup_wifi();                              // 連接WiFi
  client.setServer(mqtt_server, mqtt_port);  //連接至MQTT
}
void humi_temp() {
  temp = dht.readTemperature();
  Serial.print("-------------------------------------\n");
  Serial.print("溫度：");
  Serial.print(temp);
}
void temp_color (unsigned char red, unsigned char green, unsigned char blue) {
  analogWrite(redPin, red);
  analogWrite(greenPin,green);
  analogWrite(bluePin, blue);
}
void loop() {
  humi_temp();
  if (temp > 35) {
    Serial.print("溫度超過35，");
    temp_color(255,0,0);
  }
  if (temp >= 20 && temp <35) {
    Serial.print("溫度超過20且小於35，");
    temp_color(0,255,0);
  }
  if (temp < 20) {
    Serial.print("溫度低於20，");
    temp_color(0,0,255);
  }
  // 連接到MQTT伺服器
  if (!client.connected()) {
    reconnect();
  }
  // 啟動MQTT
  client.loop();
  String tempStr = String(temp);

  client.publish("test/temp", tempStr.c_str());
  // 向伺服器傳送HTTP
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = String(serverName) + "?temperature=" + String(temp);
    http.begin(url);            // 指定的伺服器
    int httpCode = http.GET();  // GET
    if (httpCode > 0) {  // 檢查是否有錯
      Serial.println("資料已傳送");
      Serial.print("-------------------------------------\n");
    } else {
      Serial.println("Error sending data");
    }
    http.end();  // 結束
  } else {
    Serial.println("WiFi not connected");
  }
  delay(10000); 
}
```