2018年11月10日 星期六

ESP32 MQTT – Publish and Subscribe with Arduino IDE

ESP32 MQTT – Publish and Subscribe with Arduino IDE































/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com 
*********/

#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"          // Library for DHT sensors

// Replace the next variables with your SSID/Password combination
//const char* ssid = "REPLACE_WITH_YOUR_SSID";
//const char* password = "REPLACE_WITH_YOUR_PASSWORD";
const char* ssid = "alex9ufo";
const char* password ="alex9981";

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "broker.mqtt-dashboard.com";

/* definitions for deepsleep */
#define uS_TO_S_FACTOR 1000000        /* Conversion factor for micro seconds to seconds */
//#define TIME_TO_SLEEP 900              /* Time ESP32 will go to sleep for 15 minutes (in seconds) */
//#define TIME_TO_SLEEP_ERROR 3600       /* Time to sleep in case of error (1 hour) */
#define TIME_TO_SLEEP 10               /* Time ESP32 will go to sleep for 5 seconds (in seconds) */
#define TIME_TO_SLEEP_ERROR 3         /* Time to sleep in case of error (3 sec) */

WiFiClient espClient;
PubSubClient client(espClient);

long lastMsg = 0;
char msg[50];
int value = 0;

#define DHTPIN 23              // DHT Pin
// Uncomment depending on your sensor type:
#define DHTTYPE DHT11           // DHT 11
//#define DHTTYPE DHT22         // DHT 22  (AM2302)
// Create objects
DHT dht(DHTPIN, DHTTYPE); 

float temperature = 0;
float humidity = 0;

// LED Pin
const int ledPin = 2;
//===========================================================
void setup() {
  Serial.begin(115200);
  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  //status = dht.begin(); 
  dht.begin();
  delay(700);
  humidity = (float)dht.readHumidity();
  temperature = (float)dht.readTemperature();
  if ( isnan(temperature) || isnan(humidity)) {
      Serial.println("[ERROR] Please check the DHT sensor !");
      esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);                   //go to sleep
      Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) + " Seconds");
      Serial.println("Going to sleep now because of ERROR");
      esp_deep_sleep_start();
      while (1);
   }

  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(ledPin, OUTPUT);
}
//===========================================================
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 alex9ufo/esp32/outTopic , you check if the message is either "on" or "off".
  // Changes the output state according to the message
  if (String(topic) == "alex9ufo/esp32/inTopic") {
    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/inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//===========================================================
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
   
    // Temperature in Celsius

    temperature = (float)dht.readTemperature();
   
    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
   
    Serial.print("publish to MQTT ");
    Serial.print("Temperature: ");
    Serial.println(tempString);
    client.publish("alex9ufo/esp32/temperature", tempString);

    humidity = (float)dht.readHumidity();
   
    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
 
    Serial.print("publish to MQTT ");
    Serial.print("Humidity: ");
    Serial.println(humString);
   
    client.publish("alex9ufo/esp32/humidity", humString);
  }
}
//===========================================================
Node_Red Json file


[{"id":"3960a75d.cdc408","type":"mqtt out","z":"ffd513f.cdb53f","name":"","topic":"alex9ufo/esp32/inTopic","qos":"2","retain":"","broker":"41a78e1b.8ebeb","x":360,"y":340,"wires":[]},{"id":"c247ad15.75059","type":"mqtt in","z":"ffd513f.cdb53f","name":"","topic":"alex9ufo/esp32/temperature","qos":"2","broker":"41a78e1b.8ebeb","x":140,"y":240,"wires":[["342f9b4.d486664","98725369.791f7"]]},{"id":"69dbc543.8666fc","type":"ui_switch","z":"ffd513f.cdb53f","name":"","label":"Output","group":"9d7c6798.9fc5e8","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":70,"y":340,"wires":[["3960a75d.cdc408"]]},{"id":"342f9b4.d486664","type":"debug","z":"ffd513f.cdb53f","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":401,"y":214,"wires":[]},{"id":"e81b135d.fa6b2","type":"mqtt in","z":"ffd513f.cdb53f","name":"","topic":"alex9ufo/esp32/humidity","qos":"2","broker":"41a78e1b.8ebeb","x":130,"y":120,"wires":[["4e16cb16.765c74","c7196f02.48735"]]},{"id":"4e16cb16.765c74","type":"debug","z":"ffd513f.cdb53f","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":390,"y":60,"wires":[]},{"id":"98725369.791f7","type":"ui_chart","z":"ffd513f.cdb53f","name":"","group":"9d7c6798.9fc5e8","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,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":401,"y":274,"wires":[[],[]]},{"id":"c7196f02.48735","type":"ui_gauge","z":"ffd513f.cdb53f","name":"","group":"9d7c6798.9fc5e8","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":380,"y":140,"wires":[]},{"id":"41a78e1b.8ebeb","type":"mqtt-broker","z":"","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":"9d7c6798.9fc5e8","type":"ui_group","z":"","name":"Main","tab":"89e51ea1.a64af","disp":true,"width":"6","collapse":false},{"id":"89e51ea1.a64af","type":"ui_tab","z":"","name":"Dashboard","icon":"dashboard"}]




沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...