2017年10月30日 星期一

DHT11 MQTT publisher & Subscriber + Blynk (2 WIFI ssid password)









/*  Publisher Humidity , Temperature , Humidity & Temperature  3 item data
 *  Subscribe 3 data by Arduino program Subscribe & Blynk APP
 * 
 * Use NodeMCU to drive DHT11 and send temperature/humidity value to MQTT server
 * CopyRight www.osoyoo.com
 * Software:
 * Arduino IDE(version 1.6.4+)
 * ESP8266 Board Package and the Serial Port Driver
 * MQTT Clirnt (MQTTBox here)
 * Arduino library: PubSubClient
 * Arduino library:DHT
 * Connection
 * NodeMCU DHT11 sensor
 * 3.3v    VCC
 * D3      DATA
 * GND     Ground
 *   *
 */

//=====Blynk=================================
#define BLYNK_PRINT Serial
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>   //including the library of SimpleTimer
//=====Blynk=================================
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <dht.h>
dht DHT;
// Define NodeMCU D3 pin to as temperature data pin of  DHT11
#define DHT11_PIN D3

//========================LED====================
#define LED     D0        // Led in NodeMCU at pin GPIO16 (D0).
#define BRIGHT    350*2     //max led intensity (1-500)
#define INHALE    1250*2    //Inhalation time in milliseconds.
#define PULSE     INHALE*1000/BRIGHT
#define REST      1000    //Rest Between Inhalations.
//========================LED====================

// 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 = "My ASUS";//put your wifi ssid here
const char* password = "alex9981" ;//put your wifi password here 

const char* ssid2 = "74170287";//put your wifi ssid here
const char* password2 = "24063173" ;//put your wifi password here 

//========================================================
SimpleTimer timer;
//char auth[] = "Your Auth. Key";            // You should get Auth Token in the Blynk App.
                                           // Go to the Project Settings (nut icon).
const char auth[] = "bd2c91fd614b4d478c780881d06b75b6";
float t , t1;                                   // Declare the variables
float h , h1;
//========================================================

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());
  Serial.println("MQTT-DHT11-Testing");
 
}

void callback(char* topic, byte* payload, unsigned int length)    // call back "Alex9ufo-DHT3-Command"
{
  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('%');
    //ramp decreasing intensity, Exhalation (half time):
    for (int i=BRIGHT-1;i>0;i--){
      digitalWrite(LED, LOW);          // turn the LED on.
      delayMicroseconds(i*10);          // wait
      digitalWrite(LED, HIGH);         // turn the LED off.
      delayMicroseconds(PULSE-i*10);  // wait
      i--;
      delay(0);                        //to prevent watchdog firing.
    }
  digitalWrite(LED, HIGH);
  }
  // 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, 1);
   Serial.println(' C');

   //ramp increasing intensity, Inhalation:
   for (int i=1;i<BRIGHT;i++){
      digitalWrite(LED, LOW);          // turn the LED on.
      delayMicroseconds(i*10);         // wait
      digitalWrite(LED, HIGH);         // turn the LED off.
      delayMicroseconds(PULSE-i*10);   // wait
      delay(0);                        //to prevent watchdog firing.
    }
   digitalWrite(LED, LOW);
  }
  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-DHT3-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() {
  pinMode(LED, OUTPUT);   // LED pin as output.
  //========Blynk==============
  Blynk.begin(auth, ssid2, password2);
  timer.setInterval(1000, sendUptime); 
  //========Blynk==============
  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');
}

void sendUptime()
{
   // 如果要取小數三位 *1000
   // double d1 = 30.745678;
   // double d2 = int(d1*1000+0.5)/1000; //30.746
 
  float h = (DHT.humidity);
  float h1=int(h*1000+0.5)/1000;
  float t = (DHT.temperature);
  float t1=int(t*1000+0.5)/1000;
 
  Blynk.virtualWrite(V0, t1);
  Blynk.virtualWrite(V1, h1);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  // read DHT11 sensor every 6 seconds
  if (now - lastMsg > 6000) {
     digitalWrite(LED, !digitalRead(LED));
     lastMsg = now;
     int chk = DHT.read11(DHT11_PIN);

     String msg="";
     msg= msg+ DHT.temperature;
     char message[58];
     msg.toCharArray(message,58);   
     client.publish("alex9ufo-temp-RaspiData", message);

     msg="";
     msg= msg+ DHT.humidity;
     msg.toCharArray(message,58);   
     client.publish("alex9ufo-humi-RaspiData",message);

     msg="";
     msg= msg+ DHT.temperature;
     msg = msg+"," ;
     msg=msg+DHT.humidity ;
     msg.toCharArray(message,58);

    Serial.print(" Starting Temparature ");
    Serial.print(DHT.temperature, 1);
    Serial.print('C');
    Serial.print("    Starting Humidity: " );
    Serial.print(DHT.humidity, 1);
    Serial.println('%');
 
    Serial.println(message);
     //publish sensor data to MQTT broker
    client.publish("alex9ufo-DHT11-RaspiData", message);

  }
     //=========Blynk======================
    Blynk.run();
    timer.run();
 
}

2017年10月28日 星期六

NODEMCU (ESP32) Subscribing to MQTT 3-topic



#include <ESP8266WiFi.h>
#include <PubSubClient.h>

//const char* ssid = "yourNetworkName";
//const char* password =  "yourNetworkPassword";
const char* ssid = "My ASUS";
const char* password =  "alex9981";
//const char* mqttServer = "m11.cloudmqtt.com";
const char* mqttserver = "broker.mqtt-dashboard.com";
const int mqttPort = 1883;
//const char* mqttUser = "yourMQTTuser";
//const char* mqttPassword = "yourMQTTpassword";
const char* mqttUser = "";
const char* mqttPassword = "";

WiFiClient espClient;
PubSubClient client(espClient);

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

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  Serial.println();
  Serial.println("-----------------------");

}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  client.setServer(mqttserver, mqttPort);
  client.setCallback(callback);

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {

      Serial.println("connected");  

    } else {

      Serial.print("failed with state ");
      Serial.println(client.state());
      delay(1000);

    }
  }

  client.subscribe("alex9ufo-DHT11-RaspiData");
  delay(200);
  client.subscribe("alex9ufo-temp-RaspiData");
  delay(200);
  client.subscribe("alex9ufo-humi-RaspiData");
  delay(200);

}

void loop() {
  client.loop();
}

NODEMCU (ESP32) Subscribing to MQTT topic




#include <ESP8266WiFi.h>
#include <PubSubClient.h>

//const char* ssid = "yourNetworkName";
//const char* password =  "yourNetworkPassword";
const char* ssid = "My ASUS";
const char* password =  "alex9981";
//const char* mqttServer = "m11.cloudmqtt.com";
const char* mqttserver = "broker.mqtt-dashboard.com";
const int mqttPort = 1883;
//const char* mqttUser = "yourMQTTuser";
//const char* mqttPassword = "yourMQTTpassword";
const char* mqttUser = "";
const char* mqttPassword = "";

WiFiClient espClient;
PubSubClient client(espClient);

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

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  Serial.println();
  Serial.println("-----------------------");

}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  client.setServer(mqttserver, mqttPort);
  client.setCallback(callback);


  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {

      Serial.println("connected"); 

    } else {

      Serial.print("failed with state ");
      Serial.println(client.state());
      delay(2000);

    }
  }

  client.subscribe("alex9ufo-DHT11-RaspiData");

}

void loop() {
  client.loop();
}

ESP32: Subscribing to MQTT topic

ESP32: Subscribing to MQTT topic

The objective of this post is to explain how to connect to a MQTT broker and subscribe to a topic, using the ESP32 and the Arduino IDE libraries.


Introduction

The objective of this post is to explain how to connect to a MQTT broker and subscribe to a topic, using the ESP32 and the Arduino IDE libraries.
We will assume that the broker will be hosted on CloudMQTT. We are also going to use a MQTT library, called PubSubClient, which will expose the functionality needed to connect to the broker and subscribe to a topic.
Since we have already covered most of the coding needed to connect to the broker in this previous post, we will do a shorter explanation here.


The code

First, we start by including the libraries needed for all the functionality. We need the WiFi library, in order to be able to connect the ESP32 to a WiFi network, and the PubSubClient library, which will make available the MQTT related functionalities.
After that, we declare some global variables for holding the credentials of the connections. We need the WiFi credentials, to connect to the WiFi network. We will also need the information and credentials of the MQTT server. We will need the server address, the port, the username and the password, which can be obtained in the instance information page of CloudMQTT.
Then, we will declare an object of class WiFiClient, which will allow us to create a connection to a certain IP and port. We will also declare an object of class PubSubClient, which receives as input of the constructor the previously defined WiFiClient object.
1
2
3
4
5
6
7
8
9
10
11
12
#include <WiFi.h>
#include <PubSubClient.h>
 
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
const char* mqttServer = "m11.cloudmqtt.com";
const int mqttPort = 12948;
const char* mqttUser = "yourMQTTuser";
const char* mqttPassword = "yourMQTTpassword";
 
WiFiClient espClient;
PubSubClient client(espClient);
Now, in the setup function, we will open a Serial connection, to output the results of the program. We will also establish the connection to the WiFi network.
Next, we need to specify the address and the port of the MQTT server.  To do so, we call the setServer method on the PubSubClient object. This method will receive as first argument the address and as second the port, both defined early in global variables.
Then, we use the setCallback method on the same object to specify a handling function. This handling function will be executed when a MQTT message is received on a subscribed topic. We will leave the code of this function for latter.
1
2
3
4
5
6
7
8
9
10
11
12
Serial.begin(115200);
 
WiFi.begin(ssid, password);
 
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
 
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
Next, we will connect to the MQTT server. We will do it in a loop until we get success. You can check this previous post for a more detailed explanation of the methods used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
 
      Serial.println("connected"); 
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
}
Finally, we will subscribe to the topic we want. This way, we will receive messages published on that topic from other clients. To do so, we call the subscribe method, which receives as input the name of the topic to which we want to subscribe. The topic for this tutorial will be “esp/test”.
1
client.subscribe("esp/test");


The callback function

As said before, we still need to specify the callback function, to execute when a message is received for a subscribed topic. The arguments of this callback function are the name of the topic, the payload (in bytes) and the length of the message received. The message should also return void.
As can be seen in the code bellow, we will first print the topic name and then each byte of the message received. In the end we will also print some separator characters, to differentiate messages received.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
 
  Serial.println();
  Serial.println("-----------------------");
 
}


The main loop

In the main loop function, we will need to call the loop method of the PubSubClient. As indicated in the documentation of the library, the function should be called on a regular basis,  in order to allow the client to process incoming messages and maintain the connection to the MQTT server.
1
2
3
void loop() {
client.loop();
}
Check the full code bellow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <WiFi.h>
#include <PubSubClient.h>
 
const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPassword";
const char* mqttServer = "m11.cloudmqtt.com";
const int mqttPort = 12948;
const char* mqttUser = "yourMQTTuser";
const char* mqttPassword = "yourMQTTpassword";
 
WiFiClient espClient;
PubSubClient client(espClient);
 
void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
 
  Serial.println();
  Serial.println("-----------------------");
 
}
 
void setup() {
 
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
 
      Serial.println("connected"); 
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
  }
 
  client.subscribe("esp/test");
 
}
 
void loop() {
  client.loop();
}

Testing the code

To test the code, just upload it to the ESP32 and open the Arduino IDE serial monitor.
As usual, we are also going to use MQTTLens for the tests. So, we just need to open it and publish a message to the post to which the ESP32 has subscribed, as shown in figure 1.
MQTTLens Sending message to ESP32 topic
Figure 1 – Sending message to MQTT topic, from MQTTLens.
In the Arduino IDE serial monitor, we should get a result similar to figure 2, where the message previously sent to the topic is printed. In this case, I’ve sent a couple of them.
ESP32 reading message from subscribed MQTT topic
Figure 2 – Getting messages from subscribed MQTT topic.


Related Content


Related Posts

2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2

 2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2 AngularJS 實例 <!DOCTYPE html> <html> <head> &...