#include <WiFi.h>
#include <DHT.h>
#include <PubSubClient.h>
//DHT
#define DHTPIN 14 //設定溫濕度感測器腳位
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
// 儲存訊息的字串變數
String msgStr = "";
// 儲存字元陣列格式的訊息字串(參閱下文說明)
char json[30];
// MQTT Broker
const char *mqtt_broker = "broker.MQTTGO.io";
const char *topic = "emqx/esp32";
String client_id = "7935364904";
const char *mqtt_username = "";
const char *mqtt_password = "";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(9600);
//DHT
dht.begin();
Serial.print("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
client.setServer(mqtt_broker, mqtt_port);
while (!client.connected()) {
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public EMQX MQTT broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
//DHT
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); //"temperature"存取溫濕度感測器數值
// 更新用戶端狀態
client.loop();
// 建立MQTT訊息(JSON格式的字串)
msgStr = msgStr + "溫度:" + temperature +",濕度:"+ humidity ;
// 把String字串轉換成字元陣列格式
msgStr.toCharArray(json,30);
client.publish(topic,json);
client.subscribe(topic);
// 清空MQTT訊息內容
msgStr = "";
delay(1000); // TODO: Build something amazing!
}