2017年10月23日 星期一

DHT11+MQTT-2 NodeMCU will publish realtime temperature and humidity to MQTT broke

NodeMCU will publish realtime temperature and humidity to MQTT broker every 6 seconds,you can use a MQTT client software to subscribe the topic “Alex9ufo-DHT11-Command” and see the published data from NodeMCU.
If you use MQTT client software to send a MQTT message “0” or “1” with topic “Alex9ufo-DHT11-Command”, NodeMCU will do some action as per your command. In our code, you will see message “0” will make NodeMCU print Humidity and Message “1” will make NodeMCU print temperature.











/*
 * Use NodeMCU to drive DHT11 and send temperature/humidity value to MQTT server
 * Tutorial URL http://osoyoo.com/2016/11/24/use-nodemcu-to-send-temperaturehumidity-data-to-mqtt-iot-broker/
 * CopyRight John Yu
 *  
 *  Connection Graph
 *  NodeMCU  DHT11 sensor
 *  3.3v     VCC
 *  D3       DATA
 *  GND      Ground
 *  
 */
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <dht.h>
dht DHT;

#include <Wire.h>  // This library is already built in to the Arduino IDE
#include <LiquidCrystal_I2C.h> //This library you can add via Include Library > Manage Library > 
LiquidCrystal_I2C lcd(0x27, 16, 2);   
//*0x27 means the address of this 1602 I2C LCD display,different lcd may have the different address,

// Define NodeMCU D3 pin to as temperature data pin of  DHT11
#define DHT11_PIN D3

// Update these with values suitable for your network.
//const char* ssid = "******";//put your own wifi ssid here
//const char* password = "******";// put your wifi password here
const char* ssid = "PTS-2F";//put your wifi ssid here
const char* password = "" ;//put your wifi password here

const char* mqtt_server = "broker.mqtt-dashboard.com";
//const char* mqtt_server = "iot.eclipse.org";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {
   delay(100);
  // We start by connecting to a WiFi network
    Serial.print("Connecting to ");
    Serial.println(ssid);
    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("Command is : [");
  Serial.print(topic);
  int p =(char)payload[0]-'0';
  int chk = DHT.read11(DHT11_PIN);
  // if MQTT comes a 0 message, show humidity
  if(p==0) 
  {
    Serial.println("to show humidity!]");
    Serial.print(" Humidity is: " );
    Serial.print(DHT.humidity, 1);
    Serial.println('%');
    
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Alex9ufo1602-I2C-LCD"); // Start Print text to Line 1
    lcd.setCursor(0, 1);
    lcd.print("Humidity:"); // Start Print text to Line 1
    lcd.print(DHT.humidity);
    lcd.setCursor(13,1);
    lcd.print(' %');
    
  } 
  // if MQTT comes a 1 message, show temperature
  if(p==1)
  {
  // digitalWrite(BUILTIN_LED, HIGH);
    Serial.println(" is to show temperature!] ");
  int chk = DHT.read11(DHT11_PIN);
   Serial.print(" Temp is: " );
   Serial.print(DHT.temperature);
   Serial.println(' C');
   
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print("Alex9ufo1602-I2C-LCD"); // Start Print text to Line 1
   lcd.setCursor(0, 1);
   lcd.print("Temp is:"); // Start Print text to Line 1
   lcd.print(DHT.temperature, 1);
   lcd.print((char)223);
   lcd.print("C");
  }
  Serial.println();
} //end callback

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) 
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    //if you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client.connect(clientId.c_str()))
    {
      Serial.println("connected");
     //once connected to MQTT broker, subscribe command if any
      client.subscribe("Alex9ufo-DHT11-Command");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 6 seconds before retrying
      delay(6000);
    }
  }
} //end reconnect()

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  int chk = DHT.read11(DHT11_PIN);
  Serial.print(" Starting Humidity: " );
  Serial.print(DHT.humidity, 1);
  Serial.println('%');
  Serial.print(" Starting Temparature ");
  Serial.print(DHT.temperature, 1);
  Serial.println('C');
  lcd.begin();   // initializing the LCD
  lcd.backlight(); // Enable or Turn On the backlight 
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  // read DHT11 sensor every 6 seconds
  if (now - lastMsg > 6000) {
     lastMsg = now;
     int chk = DHT.read11(DHT11_PIN);
     String msg="real time temperature: ";
     msg= msg+ DHT.temperature;
     msg = msg+" C ;real time Humidity: " ;
     msg=msg+DHT.humidity ;
     msg=msg+"%";
     char message[58];
     msg.toCharArray(message,58);
     Serial.println(message);
     //publish sensor data to MQTT broker
    client.publish("alex9ufo-DHT11-Data", message);
  }
}

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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