Arduino MQTT 搭建物联网可视化温度实时监测
所需元器件:
Ardunio UNO Wifi 开发面板 x1
DHT11 温湿度传感器 x1
10k欧姆电阻 x1
面包板x1,
连接线若干
设计电路图:
按照电路图连接电路板如下:
搭建MQTT服务器:
搭建MQTT服务选择开源软件Mosquitto,下载地址及各系统安装方法见https://mosquitto.org/download/
此实例安装于Mac系统,利用brew安装:
-
安装命令brew install mosquitto
-
安装完成后,文件目录位于/usr/local/Cellar/mosquitto/1.4.11_2/ 配置文件位于目录/usr/local/etc/mosquitto/
-
设置 mosquitto MQTT服务启动websoc监听,修改配置文件/usr/local/etc/mosquitto/mosquitto.conf
listener 1883listener 9001protocol websockets -
启动服务
/usr/local/Cellar/mosquitto/1.4.11_2/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
由于要连接MQTT服务,设置Arduino MQTT客户端连接
编写代码:
Arduino 发送数据到MQTT服务采用Arduino Ciao Library #include "DHT.h"#include #include #define CONNECTOR "mqtt"#define TOPIC "DHT11_TOPIC"// what digital pin we're connected to#define DHTPIN 7 // Uncomment whatever type you're using!#define DHTTYPE DHT11 // DHT 11// Initialize DHT sensor.// Note that older versions of this library took an optional third parameter to// tweak the timings for faster processors. This parameter is no longer needed// as the current DHT reading algorithm adjusts itself to work on faster procs.DHT dht(DHTPIN, DHTTYPE);void setup() { Serial.begin(9600); //DHT11 begin dht.begin(); //Ciao begin Ciao.begin();}
void loop() { // Wait a few seconds between measurements. delay(6000); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t)) { Serial.println("Failed to read from DHT11 sensor!"); return; } Serial.print("Humidity: "); Serial.print(h); Serial.print(" %t"); Serial.print("Temperature: "); Serial.println(t); String data = "{"H":" + String(h) +","T":" + String(t)+"}"; // pushes data into a channel Ciao.write(CONNECTOR, TOPIC,data); }
温、湿度web可视化输出:
浏览器客户端展示数据,需要与MQTT服务通讯,这里采用MQTT client mqtt.js,可视化展示采用实时数据图表可视化epoch.js
代码如下:
epoch.js mqtt.js可视化输出如下:
--end--
声明:本文章由网友投稿作为教育分享用途,如有侵权原作者可通过邮件及时和我们联系删除:freemanzk@qq.com