2018年1月31日 星期三

NodeMCU Lesson 12— Tilt Sensor & MQTT

NodeMCU Lesson 12— Tilt Sensor & MQTT

Introduction

In this lesson, we will show how to check the tilt sensor values on NodeMCU, then publish these values to a MQTT broker, so we can use the MQTT client to subscribe to corresponding topic and get these values remotely .

Preparation

Hardware:
Software:

Connection

Overhere,we use A0 as the analog input pin.

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 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:
The NodeMCU serial port will show the IP address and the connection satatus,then print the resistance value.
As you can see from the sketch,When the tilt sensor value is more than 15, the serial output is:
"0: The resistance value is: "
Let the tilt sensor go up vertically,at the same time, open the MQTT client and click "Subscribe" button on the "OsoyooData" topic,you will see the message that published by NodeMCU:
Tilt the tilt sensor or make it stand upside down,when the tilt sensor value is less than or equal to 15, the serial output is:
"1: The resistance value is: "
The output data from NodeMCU serial and MQTT client:

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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