2023年6月27日 星期二

ESP32 MQTT傳送DHT11溫溼度

 ESP32 MQTT傳送DHT11溫溼度





[{"id":"f0d37edca8bd827a","type":"ui_gauge","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":1,"width":"3","height":"2","gtype":"gage","title":"濕度","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"65","seg2":"75","className":"","x":370,"y":420,"wires":[]},{"id":"2858a2ae8ebe4d8f","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"ON","payloadType":"str","topic":"","topicType":"str","x":140,"y":80,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"9e48ae5668dd1d79","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 關","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"OFF","payloadType":"str","topic":"","topicType":"str","x":140,"y":120,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"f20d6295bed43e34","type":"mqtt out","z":"17c01e65ea7d6deb","name":"Control LED","topic":"alex9ufo/Esp32/output","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"841df58d.ee5e98","x":390,"y":180,"wires":[]},{"id":"7451665529bc4d94","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開關反向","tooltip":"","color":"blue","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TOGGLE","payloadType":"str","topic":"","topicType":"str","x":160,"y":160,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"88929da799604451","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開5秒鐘","tooltip":"","color":"purple","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TIMER","payloadType":"str","topic":"","topicType":"str","x":150,"y":240,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"1848f7d50b01e54d","type":"comment","z":"17c01e65ea7d6deb","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":270,"y":280,"wires":[]},{"id":"9861fa8e41cac265","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 閃爍","tooltip":"","color":"yellow","bgcolor":"","className":"","icon":"fa-circle-o","payload":"FLASH","payloadType":"str","topic":"","topicType":"str","x":140,"y":200,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"4411678fdec67d84","type":"ui_audio","z":"17c01e65ea7d6deb","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":true,"x":400,"y":240,"wires":[]},{"id":"9610c96e24aa9818","type":"ui_text","z":"17c01e65ea7d6deb","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":450,"y":120,"wires":[]},{"id":"b9d0a81d2ded2e3a","type":"ui_audio","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","voice":"en-US","always":"","x":380,"y":320,"wires":[]},{"id":"8d3c364c24da2ae4","type":"mqtt in","z":"17c01e65ea7d6deb","name":"Humidity","topic":"alex9ufo/Esp32/humidity","qos":"2","datatype":"auto-detect","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":180,"y":420,"wires":[["f0d37edca8bd827a","b9d0a81d2ded2e3a"]]},{"id":"c9459b13380fcebf","type":"mqtt in","z":"17c01e65ea7d6deb","name":"Temperature","topic":"alex9ufo/Esp32/temperature","qos":"2","datatype":"auto-detect","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":190,"y":360,"wires":[["1c1b88400941a7c1","b9d0a81d2ded2e3a"]]},{"id":"1c1b88400941a7c1","type":"ui_gauge","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":1,"width":"3","height":"2","gtype":"gage","title":"溫度","label":"℃","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"26","seg2":"50","className":"","x":370,"y":360,"wires":[]},{"id":"61b5589a2c26df1d","type":"mqtt in","z":"17c01e65ea7d6deb","name":"LED Status","topic":"alex9ufo/Esp32/output_status","qos":"2","datatype":"auto-detect","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":150,"y":40,"wires":[["050db70fc3c0868a"]]},{"id":"050db70fc3c0868a","type":"ui_text","z":"17c01e65ea7d6deb","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"ESP32發行到MQTT的LED狀態","format":"{{msg.payload}}","layout":"row-left","className":"","x":450,"y":40,"wires":[]},{"id":"d783cb980c3979fc","type":"ui_group","name":"Demo","tab":"0449b3b1fea99d52","order":1,"disp":true,"width":"6","collapse":false},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"6c9116b.b62d4e8","type":"ui_group","name":"Storing IOT Data ","tab":"eeb8e179.a47a4","order":1,"disp":true,"width":"6","collapse":true},{"id":"0449b3b1fea99d52","type":"ui_tab","name":"Demo","icon":"dashboard","disabled":false,"hidden":false},{"id":"eeb8e179.a47a4","type":"ui_tab","name":"eWeLink","icon":"dashboard","disabled":false,"hidden":false}]

ESP32 AutoConnected to WIFI 

#include <WiFiManager.h>         // https://github.com/tzapu/WiFiManager
#include <PubSubClient.h>
//=========================================

// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

#define DHTPIN 27     // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

// Uncomment the type of sensor in use:
//#define DHTTYPE    DHT11     // DHT 11
#define DHTTYPE    DHT22     // DHT 22 (AM2302)
//#define DHTTYPE    DHT21     // DHT 21 (AM2301)

// See guide for details on sensor wiring and usage:
//   https://learn.adafruit.com/dht/overview

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

#define BUILTIN_LED 2
// Update these with values suitable for your network.

#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;
 
String json = "";    
char jsonChar1[100];  //client.publish("alex9ufo/Esp32/temperature"
char jsonChar2[100];  //client.publish("alex9ufo/Esp32/humidity"
char jsonChar3[100];  //client.publish("alex9ufo/Esp32/output_status",

bool Flash = false;  //true
bool Timer = false;  //true
bool Send = false;  //true
int Count= 0;

DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;

//=============================================================================
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 mqttConnectedCb() {
  Serial.println("connected");
 
  // Once connected, publish an announcement...
  client.publish("alex9ufo/Esp32/temperature", jsonChar1, MQTTpubQos); // true means retain
  client.publish("alex9ufo/Esp32/humidity", jsonChar2, MQTTpubQos); // true means retain
  // Once connected, publish an announcement...
  client.publish("alex9ufo/Esp32/output_status", jsonChar3, MQTTpubQos); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/Esp32/output", 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 == "OFF")
   
   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 == "ON")
   
   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 == "TOGGLE")
   
   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] == 'FLASH')
   
    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] == 'TIMER')
   
}
//======================================================
void autoconnect() {
    // WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
    // it is a good practice to make sure your code sets wifi mode how you want it.

    // put your setup code here, to run once:
    Serial.begin(115200);
    pinMode(BUILTIN_LED, OUTPUT);

    delay(1000);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wm;

    // reset settings - wipe stored credentials for testing
    // these are stored by the esp library
    // wm.resetSettings();

    // Automatically connect using saved credentials,
    // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"),
    // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect())
    // then goes into a blocking loop awaiting configuration and will return success result

    bool res;
    // res = wm.autoConnect(); // auto generated AP name from chipid
    // res = wm.autoConnect("AutoConnectAP"); // anonymous ap
    res = wm.autoConnect("AutoConnectAP","password"); // password protected ap

    if(!res) {
        Serial.println("Failed to connect");
        // ESP.restart();
        res = wm.autoConnect("AutoConnectAP","password"); // password protected ap
    }
    else {
        //if you get here you have connected to the WiFi    
        Serial.println("connected...yeey :)");
    }

}

//======================================================
void setup() {
  autoconnect();
  // if you get here you have connected to the WiFi
  Serial.println("Connected.");

  dht.begin();
  Serial.println(F("DHTxx Unified Sensor Example"));
  // Print temperature sensor details.
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  Serial.println(F("------------------------------------"));
  Serial.println(F("Temperature Sensor"));
  Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("°C"));
  Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("°C"));
  Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("°C"));
  Serial.println(F("------------------------------------"));
  // Print humidity sensor details.
  dht.humidity().getSensor(&sensor);
  Serial.println(F("Humidity Sensor"));
  Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("%"));
  Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("%"));
  Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("%"));
  Serial.println(F("------------------------------------"));
  // Set delay between sensor readings based on sensor details.
  delayMS = sensor.min_delay / 1000;


}
//======================================================
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 loop() {
  process_mqtt();
  long now = millis();
  if (Flash)
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(500);
  }
  if (Timer)
  {
    digitalWrite(BUILTIN_LED, HIGH);
    delay(500);
    Count=Count-1;
    if (Count == 0 ){
       Timer=false;
       digitalWrite(BUILTIN_LED, LOW);
    }
     
  }
  if (Send) {
     // Convert JSON string to character array
     json.toCharArray(jsonChar3, json.length()+1);
     if  (client.connected()) {
              Serial.print("Publish message: ");
              Serial.println(json);
              // Publish JSON character array to MQTT topic
             client.publish("alex9ufo/Esp32/output_status",jsonChar3);
         }
     Send = false;    
   }
 
  if (WiFi.status() == WL_CONNECTED) {
    //========Auto Connect===============================
     if (now - lastMsg > 10000) {  //等10秒
        lastMsg = now;
        dht.begin();
        // Delay between measurements.
        delay(delayMS);
        // Get temperature event and print its value.
        sensors_event_t event;
        dht.temperature().getEvent(&event);
        if (isnan(event.temperature)) {
            Serial.println(F("Error reading temperature!"));
        }
        else {
          Serial.print(F("Temperature: "));
          Serial.print(event.temperature);
          Serial.println(F("°C"));

          String json1 =String(event.temperature);
          // Convert JSON string to character array
          json1.toCharArray(jsonChar1, json1.length()+1);
   
          if  (client.connected()) {
              Serial.print("Publish message--> Temperature: ");
              Serial.println(json1);
              // Publish JSON character array to MQTT topic
             client.publish("alex9ufo/Esp32/temperature",jsonChar1);
        }

        } // (isnan(event.temperature))


        // Get humidity event and print its value.
        dht.humidity().getEvent(&event);
        if (isnan(event.relative_humidity)) {
          Serial.println(F("Error reading humidity!"));
        }
        else {
          Serial.print(F("Humidity: "));
          Serial.print(event.relative_humidity);
          Serial.println(F("%"));
          String json1 =String(event.relative_humidity);
          // Convert JSON string to character array
          json1.toCharArray(jsonChar2, json1.length()+1);
   
          if  (client.connected()) {
              Serial.print("Publish message--> Humidity: ");
              Serial.println(json1);
              // Publish JSON character array to MQTT topic
             client.publish("alex9ufo/Esp32/humidity",jsonChar2);
        }  
        }


      } // if (now - lastMsg > 5000))
    } //========Auto Connect===============================
  //Portal.handleClient();
}   //Loop
//=========================================================


沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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