接著上次連接阿里IOT的熱情趕緊買了個小模塊測試了下解取,感覺效果還不錯斩松,阿里提供的支持還是很方便的络凿。
材料準備
-
Esp8266 D1 Mini (淘寶自行搜索) (10-20之間)別忘記配usb數(shù)據(jù)線
-
DHT11 模塊 (淘寶自行搜索)(幾塊錢)
接下來就是輕車熟路的創(chuàng)建產(chǎn)品和設(shè)備荞彼,有一點需要注意冈敛,產(chǎn)品創(chuàng)建要從另個地方創(chuàng)建,原因就是可視化應(yīng)用時候我們會搜不到設(shè)備鸣皂,這個問題我也沒仔細去查找抓谴,有知道的告訴。
上面創(chuàng)建沒什么好說的寞缝,打開查看項目
創(chuàng)建產(chǎn)品和上次創(chuàng)建步驟一樣沒什么特別注意的癌压,接下來創(chuàng)建功能自定義屬性
上面添加了三條屬性,要注意 標識符 數(shù)據(jù)類型 取值范圍 單位
標識符:設(shè)備上報數(shù)據(jù)時所對應(yīng)的Key值 很重要荆陆,不能有中文
數(shù)據(jù)類別:設(shè)備上報數(shù)據(jù)是所傳輸?shù)臄?shù)據(jù)類型
取值范圍:取值范圍根據(jù)硬件模塊設(shè)置
單位:數(shù)據(jù)單位措拇,可視化可以用到
1.Humidity
2.Temperature
3.Heat_Index
接下來創(chuàng)建一臺設(shè)備,這里可以批量創(chuàng)建慎宾,步驟3是查看設(shè)備的Key
1.接下來配置下Arduino IDE
- 文件>>>首選項 在附加開發(fā)板管理器網(wǎng)址填入>>>http://arduino.esp8266.com/stable/package_esp8266com_index.json
工具>>>開發(fā)板>>>開發(fā)板管理器
搜索esp安裝esp8266開發(fā)板
安裝后選擇開發(fā)板WEMOS D1 mini丐吓,端口號也選擇自己設(shè)備的對應(yīng)端口
2.添加開發(fā)所需要的依賴庫
-
搜索DHT 安裝DHT依賴庫
然后到上次阿里云在線開發(fā)平臺下載mqtt和阿里云的依賴
下載完成后吧zip里的文件都解壓到Arduino的libraries文件夾里。我電腦文件夾在C:\Users\Administrator\Documents\Arduino\libraries
如果這里沒有的也可以放到IDE所在目錄的libraries
搞了這么多是不是可以上代碼了趟据?
是的還有一個小坑券犁,不過問題不大,就是缺下面這個庫
下載Adafruit_Sensor添加到libraries里就好汹碱,基佬hub大家都會用吧粘衬,就不多說了。
好了接下來上代碼
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <aliyun_mqtt.h>
#include <DHT.h>
#define WIFI_SSID "WIFI名"
#define WIFI_PASSWD "WIFI密碼"
#define PRODUCT_KEY "自己設(shè)備"
#define DEVICE_NAME "自己設(shè)備"
#define DEVICE_SECRET "自己設(shè)備"
#define ALINK_BODY_FORMAT "{\"id\":\"%u\",\"version\":\"1.0\",\"method\":\"%s\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
#define ALINK_TOPIC_PROP_SET "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/service/property/set"
#define ALINK_METHOD_PROP_POST "thing.event.property.post"
//這個是DHT11模塊輸入的IO口 我這里選擇的D7 看自己需求選擇
#define DHTPIN 13
#define DHTTYPE DHT11
//這個是指示燈 又需要的可以在阿里云里添加功能
const int LED = 12;
//默認LED開啟的
int ledState = HIGH;
//推數(shù)據(jù)我這選擇15秒推一次 我發(fā)現(xiàn)推的快了數(shù)據(jù)還是跑的很快的,畢竟阿里消息數(shù)>百萬也是要錢的哦
unsigned long delayTime = 15000;
unsigned long lastDebounceTime = 0;
unsigned long lastMqttConnectMs = 0;
unsigned int postMsgId = 0;
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void initWifi(const char *ssid, const char *password)
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("WiFi does not connect, try again ...");
delay(3000);
}
Serial.println("Wifi is connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void mqttCheckConnect()
{
bool connected = connectAliyunMQTT(mqttClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET);
if (connected) {
Serial.println("MQTT connect succeed!");
if (mqttClient.subscribe(ALINK_TOPIC_PROP_SET)) {
Serial.println("subscribe done.");
} else {
Serial.println("subscribe failed!");
}
}
}
//上報檢測數(shù)據(jù)
void mqttPublish()
{
char param[512];
char jsonBuf[1024];
float h = dht.readHumidity();//濕度
float t = dht.readTemperature();//溫度
float hic = dht.computeHeatIndex(t, h, false);//熱指數(shù)
sprintf(param, "{\"LED_STATE\":%d,\"Humidity\":%.2f,\"Temperature\":%.2f,\"Heat_Index\":%.2f}", ledState, isnan(h) ? 0 : h, isnan(t) ? 0 : t, isnan(hic) ? 0 : hic);
postMsgId += 1;
sprintf(jsonBuf, ALINK_BODY_FORMAT, postMsgId, ALINK_METHOD_PROP_POST, param);
if (mqttClient.publish(ALINK_TOPIC_PROP_POST, jsonBuf)) {
Serial.print("Post message to cloud: ");
Serial.println(jsonBuf);
} else {
Serial.println("Publish message to cloud failed!");
}
}
void callback(char* topic, byte* payload, unsigned int length)
{
if (strstr(topic, ALINK_TOPIC_PROP_SET))
{
Serial.print("Set message arrived [");
Serial.print(topic);
Serial.print("] ");
payload[length] = '\0';
Serial.println((char *)payload);
// Deserialization break change from 5.x to 6.x of ArduinoJson
DynamicJsonDocument doc(100);
DeserializationError error = deserializeJson(doc, payload);
if (error)
{
Serial.println("parse json failed");
return;
}
JsonObject setAlinkMsgObj = doc.as<JsonObject>();
// LightSwitch
int desiredLedState = setAlinkMsgObj["params"]["LED_STATE"];
if (desiredLedState == HIGH || desiredLedState == LOW) {
ledState = desiredLedState;
const char* cmdStr = desiredLedState == HIGH ? "on" : "off";
Serial.print("Cloud command: Turn ");
Serial.print(cmdStr);
Serial.println(" the light.");
}
}
}
void setup() {
Serial.begin(115200);
Serial.println("Hacklab MQTT LED demo starts.");
pinMode(LED, OUTPUT);
dht.begin();
initWifi(WIFI_SSID, WIFI_PASSWD);
mqttClient.setCallback(callback);
lastMqttConnectMs = millis();
mqttCheckConnect();
mqttPublish();
}
void loop() {
if (millis() - lastMqttConnectMs >= delayTime) {
lastMqttConnectMs = millis();
mqttCheckConnect();
}
if (!mqttClient.loop()) {
Serial.println("The MQTT client is disconnected!");
}
if (millis() - lastDebounceTime >= delayTime) {
if (ledState == HIGH) {
Serial.println("Turn on light locally.");
} else {
Serial.println("Turn off light locally.");
}
lastDebounceTime = millis();
mqttPublish();
Serial.println(lastDebounceTime);
}
digitalWrite(LED, ledState);
}