2017年10月18日 星期三

Use NodeMcu send message to MQTT BROKER







/*
 * 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
 */
 /* NodeMCU Pin assigment
  GPIO Pin  I/O Index Number
  GPIO0  3   GPIO1  10 GPIO2  4    GPIO3  9     GPIO4  2   GPIO5   1   GPIO6  N/A  GPIO7  N/A
  GPIO8  N/A GPIO9  11 GPIO10  12  GPIO11   N/A GPIO12  6  GPIO13  7   GPIO14   5  GPIO15   8   GPIO16   0 */

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

// Define NodeMCU D3 pin to as temperature data pin of  DHT11
#define DHT11_PIN D3   //GPIO0  3
DHT dht(DHT11_PIN, DHT11);

// Update these with values suitable for your network.
//const char* ssid = "your_hotspot_ssid";
//const char* password = "your_hotspot_password";
const char* ssid = "74170287";
const char* password = "24063173";

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.readHumidity(), 1);
    Serial.println('%');
  }
  // 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.readTemperature(), 1);
   Serial.println(' 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("OsoyooCommand");
    } 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.readHumidity(), 1);
  Serial.println('%');
  Serial.print(" Starting Temparature ");
  Serial.print( dht.readTemperature(), 1);
  Serial.println('C');
}

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.readTemperature();
     msg = msg+" C ;real time Humidity: " ;
     msg=msg+dht.readHumidity() ;
     msg=msg+"%";
     char message[58];
     msg.toCharArray(message,58);
     Serial.println(message);
     //publish sensor data to MQTT broker
    client.publish("Alex9ufo DHT11", message);
  }
}

沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...