本文是這次物聯網項目的終結篇。本文將演示如何整合以前的文章中的模塊和代碼,來簡單的完成一個物聯網項目。最終的實現效果是:利用Iphone手機上的MQTTool App,來獲取DHT11的溫溼度數據,以及控制繼電器的開合。html
在閱讀本文前,你可能須要閱讀下面的文章:git
須要修改下面的server、port等相關參數,以適配本身實際的使用環境。而後下載到Arduino板中。服務器
#include <stdint.h> #include <Obloq.h> #include <SoftwareSerial.h> #include <dht11.h> #define RELAY_PIN 8 //驅動繼電器模塊的引腳 #define DHT11_PIN 9 //驅動DHT11傳感器的引腳 unsigned long prev_time=0; //上一次發佈溫溼度的時間 uint8_t temperature ,humidity ; //保存溫度和溼度 const String server = "www.lulipro.com"; //MQTT服務器的IP或者主機名 const String port= "1883"; //MQTT服務器的端口 const String iotId = "user1"; //MQTT服務器的用戶名 const String iotPwd = "abcd1234"; //MQTT服務器的密碼 const String topic_led = "home/led_ctrl"; //訂閱的主題 const String topic_dht11 = "home/temp_hum"; //訂閱的主題 const String wifiSSID = "TP-LINK12345"; //obloq模塊鏈接的WIFI名,改爲你用的WIFI名,最好不要有中文 const String wifiPwd = "aaaabbbb"; //obloq模塊鏈接的WIFI密碼,改爲你用的WIFI密碼 SoftwareSerial obloqModuleSerial(10,11); // 建立一個軟串口,用於和obloq模塊進行通訊:10是其RX(接Obloq的TX) , 11是其TX(接Obloq的RX) Obloq olq(&obloqModuleSerial,wifiSSID,wifiPwd,server,port,iotId,iotPwd); //若是你須要使用本身的MQTT服務器的話,就使用這個構造函數,並指定MQTT服務器的IP和通訊端口。 //已監聽設備的消息回調函數,能夠在這個函數裏面對接收的消息作判斷和相應處理,須要用setMsgHandle()來設置這個回調函數 void msgHandle(const String& topic,const String& message) { if(topic==topic_led) { if(message == "off") //若是收到了關於topic1主題的"off"消息,則關閉繼電器 { digitalWrite(RELAY_PIN,LOW); } else if(message == "on") //若是收到了關於topic1主題的"on"消息,則打開繼電器 { digitalWrite(RELAY_PIN,HIGH); } } } void setup(void) { obloqModuleSerial.begin(9600); //obloq模塊的串口通訊波特率是9600,因此要把軟串口的波特率也設置爲9600 olq.setMsgHandle(msgHandle);//註冊消息回掉函數 olq.subscribe(topic_led); //訂閱主題 DHT11_init(DHT11_PIN); pinMode(RELAY_PIN,OUTPUT); digitalWrite(RELAY_PIN,LOW); } void loop(void) { olq.update(); //輪詢 if(millis() - prev_time > 2000) //每隔2s發佈一次溫溼度數據 { if(DHT11_read(&temperature,&humidity)) { olq.publish(topic_dht11,String(temperature)+"&"+String(humidity)); //格式 :溫度&溼度 prev_time=millis(); } } }