2018年1月31日 星期三

NodeMCU Lesson 7 — Switch Button & MQTT

  NodeMCU Lesson 7 — Switch Button & MQTT

Introduction

In this lesson, we will connect a switch button to the NodeMCU ,and send the switch status to a MQTT broker. When the button is pressed, NodeMCU will publish the button status "pressed" to MQTT broker and the MQTT client will subscribe to these messages. When the push button is released, "not pressed" will be sent.

Preparation

Hardware:
Software:

Connection

In this lesson,we use D2(GPIO4) to control the switch,the connection is as below:
Note: This 1 k resistor is using as a pull down resistor, In such a circuit, when the switch is closed, the NodeMCU  input is at a logical high value, but when the switch is open, the pull-down resistor pulls the input voltage down to ground (logical zero value), preventing an undefined state at the input.

Upload Sketch

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 name and password setting is ok and MQTT broker is connected, open the Serial Monitor,you will see following result:Keep pressing this button,the Serial Monitor will output "Button status: Pressed" every 2 second;once release this button,the Serial Monitor will output "Button status: Not Pressed" every 2 second.
At the same time,open the MQTT client and click "Subcribe" ,you will see the button status as below:

沒有留言:

張貼留言

MQTT Explorer 與 Node-Red 介面的實驗

 MQTT Explorer 與 Node-Red 介面的實驗 MQTT EXplorer 與 Node-Red介面的設定 (1) 設定  MQTT EXplorer Client    (2)        Node-Red LED ON  --> MQTT Explor...