2018年1月31日 星期三

NodeMCU Lesson 8 — DHT11&MQTT

NodeMCU Lesson 8 — DHT11&MQTT


Introduction

In this lesson, we will show how to get the real-time environment temperature/humidity data by using NodeMCU and DHT11, then send the data to an MQTT broker via MQTT protocol, the MQTT client will subscribe to these messages.

Preparation

Hardware:
Software:

Connection

NodeMCUDHT11 sensor
3.3vVCC
D3DATA
GNDGround

Upload Sketch

Connect the NodeMCU to computer via USB cable,open this sketch by using Arduino IDE(Version1.6.4+):
Edit the code to fit your own WiFi and MQTT settings as following operations:
1)Hotspot Configration:
const char* ssid = "your_hotspot_ssid";
const char* password = "your_hotspot_password";
Find above code line,put your own ssid and password on there.
2)MQTT  Server  Address Setting
const char* mqtt_server = "broker.mqtt-dashboard.com";
You can use your own MQTT broker URL or IP address to set above mqtt_server value. You can also use some famous free MQTT server to test the project such as  "broker.mqtt-dashboard.com",  "iot.eclipse.org" etc.
3)MQTT Client Settings
If your MQTT broker require clientID,username and password authentication,you need to change
if (client.connect(clientId.c_str()))
to
if (client.connect(clientId,userName,passWord)) //put your clientId/userName/passWord here
If not,just keep them as default.
After do that,choose the coresponding board type and port type as below,then upload the sketch to the NodeMCU.
  • Board:"NodeMCU 0.9(ESP-12 Module)"
  • CPU Frequency:"80MHz"
  • Flash Size:"4M (3M SPIFFS)"
  • Upload Speed:"115200"
  • Port: Choose your own Serial Port for your NodeMCU

MQTT Client Settings

About how to config the MQTT client,check this link.
Topics Settings:
  • Topic to publish: OsoyooCommand
  • Topic to subscribe: OsoyooData

Running Result

Onece the upload done,if wifi hotspot ssid and password setting is ok, all the connections are normal, open the Serial Monitor,you will see following result: the NodeMCU serial port keep output real-time humidity and temperature data every 6 second,and these messages will be published to the MQTT broker via MQTT protocol,then they will be  subscribed by the MQTT client.
At the same time,open the MQTT client and choose subscribe to a topic called "OsoyooData" ,you will see the real-time humidity and temperature data as below:
On the MQTT publish topic side,once you publish the payload "0" or "1" to the topic "OsoyooCommand", the NodeMCU will subscribe these payloads and make a feedback. If the payload is "0",the NodeMCU get the real-time humidity data from DHT11, then print it on its serial port;If the payload is "1",the NodeMCU will output the real-time temperature dat:
.

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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