2024年7月20日 星期六

WOKWI _DHT22_Esp32_MQTT_NodeRED

WOKWI _DHT22_Esp32_MQTT_NodeRED


client.subscribe("alex9ufo/esp32/LED");

client.publish("alex9ufo/esp32/temperature", temp.c_str());
 
client.publish("alex9ufo/esp32/humidity", hum.c_str());









































WOKWI 程式



#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
#include <ArduinoJson.h>

const int DHT_PIN = 15;
const int LED_PIN = 2;

DHTesp dhtSensor;

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
float temp = 0;
float hum = 0;
int value = 0;
//======================================================================================
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//======================================================================================
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String message="";
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    message += ((char)payload[i]);
  }
  Serial.println();
  message.trim();
  // Switch on the LED if an 1 was received as first character
  if (String(topic) == "alex9ufo/esp32/LED") {
    Serial.print("Changing output to ");
    if(message == "on"){
      digitalWrite(LED_PIN, LOW);
    }
    else if(message == "off"){
      digitalWrite(LED_PIN, HIGH);
    }
  }
}

//======================================================================================
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("Connected");
      // Once connected, publish an announcement...
      //client.publish("alex9ufo/esp32", "iotfrontier");

      // ... and resubscribe
      client.subscribe("alex9ufo/esp32/LED");
    } 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() {
  pinMode(LED_PIN, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  digitalWrite(LED_PIN, HIGH);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}
//======================================================================================
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    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":"583f0b243b76dcfb","type":"debug","z":"663d84419464c1bb","name":"debug  ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":350,"y":160,"wires":[]},{"id":"dfca4f0bac560241","type":"mqtt in","z":"663d84419464c1bb","name":"temperature","topic":"alex9ufo/esp32/temperature","qos":"0","datatype":"auto-detect","broker":"2380dcc0d36d2c6a","nl":false,"rap":true,"rh":0,"inputs":0,"x":190,"y":160,"wires":[["583f0b243b76dcfb","6111ea979ef12f69"]]},{"id":"0a38ae48ebd01c2c","type":"mqtt in","z":"663d84419464c1bb","name":"humidity","topic":"alex9ufo/esp32/humidity","qos":"0","datatype":"auto-detect","broker":"2380dcc0d36d2c6a","nl":false,"rap":true,"rh":0,"inputs":0,"x":180,"y":260,"wires":[["7e40988d269b5f4f","218248ed02fedb0d"]]},{"id":"7e40988d269b5f4f","type":"debug","z":"663d84419464c1bb","name":"debug  ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":350,"y":260,"wires":[]},{"id":"218248ed02fedb0d","type":"ui_chart","z":"663d84419464c1bb","name":"","group":"2068daa4fbffb834","order":1,"width":0,"height":0,"label":"chart","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":350,"y":300,"wires":[[]]},{"id":"6111ea979ef12f69","type":"ui_gauge","z":"663d84419464c1bb","name":"","group":"f64e1fe3358c5078","order":1,"width":0,"height":0,"gtype":"gage","title":"gauge","label":"°C","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"20","seg2":"50","className":"","x":350,"y":220,"wires":[]},{"id":"f74212f0fa165a21","type":"ui_button","z":"663d84419464c1bb","name":"","group":"162a5ed3f7b99560","order":1,"width":0,"height":0,"passthru":false,"label":"ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"on","payloadType":"str","topic":"topic","topicType":"msg","x":170,"y":340,"wires":[["52d60600147bb655"]]},{"id":"19da8774110add6a","type":"ui_button","z":"663d84419464c1bb","name":"","group":"162a5ed3f7b99560","order":2,"width":0,"height":0,"passthru":false,"label":"OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"off","payloadType":"str","topic":"topic","topicType":"msg","x":170,"y":400,"wires":[["52d60600147bb655"]]},{"id":"52d60600147bb655","type":"mqtt out","z":"663d84419464c1bb","name":"LED_control","topic":"alex9ufo/esp32/LED","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"2380dcc0d36d2c6a","x":370,"y":380,"wires":[]},{"id":"2380dcc0d36d2c6a","type":"mqtt-broker","name":"","broker":"broker.hivemq.com","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"2068daa4fbffb834","type":"ui_group","name":"humidity","tab":"f304c5db6c1258cc","order":2,"disp":true,"width":"6","collapse":false,"className":""},{"id":"f64e1fe3358c5078","type":"ui_group","name":"temperature","tab":"f304c5db6c1258cc","order":1,"disp":true,"width":"6","collapse":false,"className":""},{"id":"162a5ed3f7b99560","type":"ui_group","name":"LED_control","tab":"f304c5db6c1258cc","order":3,"disp":true,"width":"6","collapse":false,"className":""},{"id":"f304c5db6c1258cc","type":"ui_tab","name":"WOKWI_DHT22","icon":"dashboard","order":127,"disabled":false,"hidden":false}]

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...