2020年12月17日 星期四

ESP32 MQTT – Publish DHT11/DHT22 Temperature and Humidity Readings (Arduino IDE)

ESP32 MQTT – Publish DHT11/DHT22 Temperature and Humidity Readings (Arduino IDE)


參考來源 https://randomnerdtutorials.com/esp32-mqtt-publish-dht11-dht22-arduino/ 

DHTesp.h  來源 https://github.com/beegee-tokyo/DHTesp






Arduino程式

#include <WiFi.h>

#include <PubSubClient.h>

#include <SPI.h>

#include <AutoConnect.h>

#include <WebServer.h>

WebServer server;

AutoConnect  Portal(server);

#define BUILTIN_LED 2

//=========================================


#define MQTTid              ""                           //id of this mqtt client

#define MQTTip              "broker.mqtt-dashboard.com"  //ip address or hostname of the mqtt broker

#define MQTTport            1883                         //port of the mqtt broker

#define MQTTuser            "alex9ufo"                   //username of this mqtt client

#define MQTTpsw             "alex1234"                   //password of this mqtt client

//#define MQTTuser          "your_username"              //username of this mqtt client

//#define MQTTpsw           "your_password"              //password of this mqtt client

#define MQTTpubQos          2                            //qos of publish (see README)

#define MQTTsubQos          1                            //qos of subscribe


//Variables

long lastMsg = 0;

char jsonChar1[100];

char jsonChar2[100];


String json = "";

bool Flash = false;  //true

bool Timer = false;  //true

bool Send = false;  //true

int Count= 0;

//=============================================================================

/* 

 * ESP32 NodeMCU DHT11 - Humidity Temperature Sensor Example

 * https://circuits4you.com

 * 

 * References

 * https://circuits4you.com/2017/12/31/nodemcu-pinout/

 * 

 */

#include "DHTesp.h"

#define DHTpin 15    //D15 of ESP32 DevKit

DHTesp dht;

//=============================================================================

boolean pendingDisconnect = false;

void mqttConnectedCb(); // on connect callback

void mqttDisconnectedCb(); // on disconnect callback

void mqttDataCb(char* topic, byte* payload, unsigned int length); // on new message callback


WiFiClient wclient;

PubSubClient client(MQTTip, MQTTport, mqttDataCb, wclient);

//======================================================

void rootPage() {

  char content[] = "Hello, world";

  server.send(200, "text/plain", content);

}  

//======================================================== 

void mqttConnectedCb() {

  Serial.println("connected");

  

  // Once connected, publish an announcement...

  client.publish("alex9ufo/esp32/dht/humidity", jsonChar1, MQTTpubQos, true); // true means retain

  // Once connected, publish an announcement...

  client.publish("alex9ufo/esp32/dht/temperature", jsonChar2, MQTTpubQos, true); // true means retain

  // ... and resubscribe

  client.subscribe("alex9ufo/esp32/inTopic", MQTTsubQos);

}

//======================================================= 

void mqttDisconnectedCb() {

  Serial.println("disconnected");

}

//=======================================================

void mqttDataCb(char* topic, byte* payload, unsigned int length) {


  /*

  you can convert payload to a C string appending a null terminator to it;

  this is possible when the message (including protocol overhead) doesn't

  exceeds the MQTT_MAX_PACKET_SIZE defined in the library header.

  you can consider safe to do so when the length of topic plus the length of

  message doesn't exceeds 115 characters

  */

  char* message = (char *) payload;

  message[length] = 0;


  Serial.print("Message arrived [");

  Serial.print(topic);

  Serial.print("] ");

  Serial.println(message);

  String s = message;


  s.trim();

  // Switch on the LED if an 1 was received as first character

  if (s == "OFF") {

     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level

     // but actually the LED is on; this is because 

     Serial.println("Received OFF , Send LOW TO BuildIn_LED");

     Flash = false;

     Timer = false;

     json ="OFF";

     Send = true ;

    } 

   if (s == "ON") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received ON , Send HIGH TO BuildIn_LED");

     Flash = false; 

     Timer = false; 

     json ="ON";

     Send = true ;

   }

   if (s == "TOGGLE") {

     digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));   // Turn the LED toggle 

     // but actually the LED is on; this is because

     Serial.println("Received TOGGLE , Send Toggle(H->L , L->H) TO BuildIn_LED");

     Flash = false; 

     Timer = false; 

     json ="TOGGLE";

     Send = true ;     

   }

   

    if (s == "FLASH") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received FLASH , Flashing BuildIn_LED ");

     Flash = true;

     Timer = false;

     json ="FLASH";

     Send = true ;  

     

   } //if (message[0] == '2')

   

    if (s == "TIMER") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received TIMER ,  BuildIn_LED ON 5 SEC");

     Flash = false;

     Timer = true;

     Count= 10;

     json ="TIMER";

     Send = true ; 

     

   } //if (message[0] == '2')

    

}

//======================================================

void process_mqtt() {

  if (WiFi.status() == WL_CONNECTED) {

    if (client.connected()) {

      client.loop();

    } else {

    // client id, client username, client password, last will topic, last will qos, last will retain, last will message

      if (client.connect(MQTTid, MQTTuser, MQTTpsw, MQTTid "/status", 2, true, "0")) {

          pendingDisconnect = false;

          mqttConnectedCb();

      }

    }

  } else {

    if (client.connected())

      client.disconnect();

  }

  if (!client.connected() && !pendingDisconnect) {

    pendingDisconnect = true;

    mqttDisconnectedCb();

  }

}

//======================================================= 

void setup()

{

  Serial.begin(115200);

  pinMode(BUILTIN_LED, OUTPUT);

  Serial.println();

  //=================================================

  Serial.println("Configuring your Mobile WiFi to esp32ap...");

  Serial.println("Configuring another WiFi SSID,PWD...");

  

  server.on("/", rootPage);

  if (Portal.begin()) {

    Serial.println("HTTP server:" + WiFi.localIP().toString());

  }

    else {

    Serial.println("Connection failed");

    while(true) {yield();}

  }

  //=================================================== 

  

  Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)\tHeatIndex (C)\t(F)");

  

  // Autodetect is not working reliable, don't use the following line

  // dht.setup(17);


  // use this instead: 

  //dht.setup(DHTpin, DHTesp::DHT11); //for DHT11 Connect DHT sensor to GPIO 17

  dht.setup(DHTpin, DHTesp::DHT22); //for DHT22 Connect DHT sensor to GPIO 17

}

//======================================================

void loop()

{

  process_mqtt();

  long now = millis();


  

  delay(dht.getMinimumSamplingPeriod());


  float humidity = dht.getHumidity();

  float temperature = dht.getTemperature();


  Serial.print(dht.getStatusString());

  Serial.print("\t");

  Serial.print(humidity, 1);

  Serial.print("\t\t");

  Serial.print(temperature, 1);

  Serial.print("\t\t");

  Serial.print(dht.toFahrenheit(temperature), 1);

  Serial.print("\t\t");

  Serial.print(dht.computeHeatIndex(temperature, humidity, false), 1);

  Serial.print("\t\t");

  Serial.println(dht.computeHeatIndex(dht.toFahrenheit(temperature), humidity, true), 1);


  // Convert data to JSON string 

  String json1 =

         "{\"data\":{"

         "\"humidity\": \"" + String(humidity) + "\"}"

         "}";

         // Convert JSON string to character array

  json1.toCharArray(jsonChar1, json1.length()+1);


  // Convert data to JSON string 

  String json2 =

         "{\"data\":{"

         "\"temperature\": \"" + String(temperature) + "\"}"

         "}";

         // Convert JSON string to character array

  json2.toCharArray(jsonChar2, json2.length()+1);

    

  if  (client.connected()) {

       // Publish JSON character array to MQTT topic

       client.publish("alex9ufo/esp32/dht/humidity",jsonChar1);

       Serial.println("Publish Topic: alex9ufo/esp32/dht/humidit ");

       Serial.print("Publish message: ");

       Serial.println(json1);

       //===============================================

       // Publish JSON character array to MQTT topic

       client.publish("alex9ufo/esp32/dht/temperature",jsonChar2);

       Serial.println("Publish Topic: alex9ufo/esp32/dht/temperature ");

       Serial.print("Publish message: ");

       Serial.println(json2);

       } 

  Portal.handleClient();

  

}//Loop

//=========================================================

Node-Red程式

[{"id":"f442f064.470ec","type":"mqtt out","z":"8e481a7f.02c558","name":"","topic":"alex9ufo/esp32/inTopic","qos":"2","retain":"","broker":"41a78e1b.8ebeb","x":560,"y":380,"wires":[]},{"id":"b516a5b3.3ff158","type":"mqtt in","z":"8e481a7f.02c558","name":"","topic":"alex9ufo/esp32/dht/temperature","qos":"1","datatype":"auto","broker":"41a78e1b.8ebeb","x":310,"y":260,"wires":[["34d900d4.8ccc2","313886f6.f6b72a"]]},{"id":"e82f5953.0e28a8","type":"ui_switch","z":"8e481a7f.02c558","name":"","label":"LED 控制 ON OFF ","tooltip":"","group":"37de8fe8.46846","order":0,"width":"6","height":"2","passthru":true,"decouple":"false","topic":"","style":"","onvalue":"ON","onvalueType":"str","onicon":"","oncolor":"","offvalue":"OFF","offvalueType":"str","officon":"","offcolor":"","x":290,"y":380,"wires":[["f442f064.470ec"]]},{"id":"34d900d4.8ccc2","type":"debug","z":"8e481a7f.02c558","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":610,"y":260,"wires":[]},{"id":"823c54be.128a38","type":"mqtt in","z":"8e481a7f.02c558","name":"","topic":"alex9ufo/esp32/dht/humidity","qos":"2","datatype":"auto","broker":"41a78e1b.8ebeb","x":300,"y":100,"wires":[["778fb64.346fb48","eaeaad3e.3d45d"]]},{"id":"778fb64.346fb48","type":"debug","z":"8e481a7f.02c558","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":550,"y":100,"wires":[]},{"id":"3e59c73e.6a5318","type":"ui_gauge","z":"8e481a7f.02c558","name":"","group":"37de8fe8.46846","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","x":640,"y":160,"wires":[]},{"id":"ae91ce9c.ac197","type":"ui_gauge","z":"8e481a7f.02c558","name":"","group":"37de8fe8.46846","order":2,"width":0,"height":0,"gtype":"gage","title":"Temperature","label":"units","format":"{{value}}","min":0,"max":"50","colors":["#00b500","#e6e600","#ca3838"],"seg1":"38","seg2":"39","x":650,"y":320,"wires":[]},{"id":"eaeaad3e.3d45d","type":"function","z":"8e481a7f.02c558","name":"","func":"var thenum = msg.payload.replace( /^\\D+/g, ''); // replace all leading non-digits with nothing\nmsg.payload=thenum;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":490,"y":160,"wires":[["3e59c73e.6a5318"]]},{"id":"313886f6.f6b72a","type":"function","z":"8e481a7f.02c558","name":"","func":"var thenum = msg.payload.replace( /^\\D+/g, ''); // replace all leading non-digits with nothing\nmsg.payload=thenum;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":510,"y":320,"wires":[["ae91ce9c.ac197"]]},{"id":"41a78e1b.8ebeb","type":"mqtt-broker","name":"mqtt","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"37de8fe8.46846","type":"ui_group","name":"DHT","tab":"53b8c8f9.cfbe48","order":1,"disp":true,"width":"6","collapse":false},{"id":"53b8c8f9.cfbe48","type":"ui_tab","name":"Home","icon":"dashboard","order":2,"disabled":false,"hidden":false}]



沒有留言:

張貼留言

2024產專班 作業2

 2024產專班 作業2   1. 系統圖       ESP32+MFRC522 組成RFID Reader 可以將RFID卡片的UID 透過 MQTT協定    上傳(發行 主題 (:topic) alex9ufo/2024/RFID/RFID_UID  ,, Payload...