ESP32 MQTT – Publish and Subscribe with Arduino IDE (WOKWI)
系統圖
WOKWI電路圖
MQTT Box
Node-Red
WOKWI程式
#include "WiFi.h";
#include <PubSubClient.h>;
#include <Wire.h>;
#include "DHTesp.h";
// DHT22 Pin
const int DHT_PIN = 15;
// LED Pin
const int ledPin = 4;
// Replace the next variables with your SSID/Password combination
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "broker.mqttgo.io";
///const char* mqtt_server = "broker.hivemq.com";
//onst char* mqtt_server = "test.mosquitto.org" ;
WiFiClient espClient;
PubSubClient client(espClient);
DHTesp dhtSensor;
long lastMsg = 0;
//=================================================================
//===================================================================
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//===================================================================
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
// Changes the output state according to the message
if (String(topic) == "alex9ufo/esp32/output") {
Serial.print("Changing output to ");
if(messageTemp == "on"){
Serial.println("on");
digitalWrite(ledPin, HIGH);
}
else if(messageTemp == "off"){
Serial.println("off");
digitalWrite(ledPin, LOW);
}
}
}
//===================================================================
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client")) {
Serial.println("connected");
// Subscribe
client.subscribe("alex9ufo/esp32/output");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//===================================================================
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
client.subscribe("alex9ufo/esp32/output");
}
//===================================================================
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
TempAndHumidity data = dhtSensor.getTempAndHumidity();
String temp = String(data.temperature, 2);
Serial.print("Temperature: ");
Serial.println(temp);
client.publish("alex9ufo/esp32/temperature", temp.c_str());
String hum = String(data.humidity, 1);
Serial.print("Humidity: ");
Serial.println(hum);
client.publish("alex9ufo/esp32/humidity", hum.c_str());
}
}
//===================================================================
Node-Red程式
[{"id":"9e58624.7faaba","type":"mqtt out","z":"46d55d9e427d2a08","name":"output","topic":"alex9ufo/esp32/output","qos":"","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"70940176.2b2d3","x":270,"y":320,"wires":[]},{"id":"abf7079a.653be8","type":"mqtt in","z":"46d55d9e427d2a08","name":"temperature","topic":"alex9ufo/esp32/temperature","qos":"2","datatype":"auto-detect","broker":"70940176.2b2d3","nl":false,"rap":false,"inputs":0,"x":144,"y":227,"wires":[["cc79021b.9a751","21eae8f8.2971b8"]]},{"id":"83cf37cf.c76988","type":"ui_switch","z":"46d55d9e427d2a08","name":"","label":"Output","group":"61285987.c20328","order":0,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"","style":"","onvalue":"on","onvalueType":"str","onicon":"","oncolor":"","offvalue":"off","offvalueType":"str","officon":"","offcolor":"","x":149,"y":320,"wires":[["9e58624.7faaba"]]},{"id":"cc79021b.9a751","type":"debug","z":"46d55d9e427d2a08","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":361,"y":194,"wires":[]},{"id":"4aecba01.78ce64","type":"mqtt in","z":"46d55d9e427d2a08","name":"humidity","topic":"alex9ufo/esp32/humidity","qos":"2","datatype":"auto-detect","broker":"70940176.2b2d3","nl":false,"rap":false,"inputs":0,"x":133,"y":111,"wires":[["22efa7b7.544a28","df37e6b7.64c1c8"]]},{"id":"22efa7b7.544a28","type":"debug","z":"46d55d9e427d2a08","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":350,"y":78,"wires":[]},{"id":"21eae8f8.2971b8","type":"ui_chart","z":"46d55d9e427d2a08","name":"","group":"61285987.c20328","order":0,"width":0,"height":0,"label":"Temperature","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"useUTC":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"outputs":1,"useDifferentColor":false,"className":"","x":361,"y":254,"wires":[[]]},{"id":"df37e6b7.64c1c8","type":"ui_gauge","z":"46d55d9e427d2a08","name":"","group":"61285987.c20328","order":0,"width":0,"height":0,"gtype":"gage","title":"Humidity","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#00b3d9","#0073e6","#001bd7"],"seg1":"33","seg2":"66","className":"","x":340,"y":138,"wires":[]},{"id":"70940176.2b2d3","type":"mqtt-broker","name":"","broker":"broker.mqttgo.io","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"sessionExpiry":""},{"id":"61285987.c20328","type":"ui_group","name":"Main","tab":"e7c46d5e.a1283","order":1,"disp":true,"width":"6","collapse":false},{"id":"e7c46d5e.a1283","type":"ui_tab","name":"Dashboard","icon":"dashboard"}]
沒有留言:
張貼留言