X
首页
技术
模拟电子
单片机
半导体
电源管理
嵌入式
传感器
最能打国产芯
应用
汽车电子
工业控制
家用电子
手机便携
安防电子
医疗电子
网络通信
测试测量
物联网
最能打国产芯
大学堂
首页
直播
专题
TI 培训
论坛
汽车电子
国产芯片
电机驱动控制
电源技术
单片机
模拟电子
PCB设计
电子竞赛
DIY/开源
嵌入式系统
医疗电子
颁奖专区
【厂商专区】
【电子技术】
【创意与实践】
【行业应用】
【休息一下】
最能打国产芯
活动中心
直播
发现活动
颁奖区
电子头条
参考设计
下载中心
分类资源
文集
排行榜
电路图
Datasheet
最能打国产芯
DigiKey得捷技术专区
[作品提交] 【Follow me第二季第2期】开发板读取 SHT40 数据并上传至 Home Assistant
lijinlei
2024-9-26 20:13
楼主
# 【Follow me第二季第2期】开发板读取 SHT40 数据并上传至 Home Assistant 本章节的任务是开发板读取SHT40传感器数据并通过MQTT协议上传至EMQX服务器并在 HA 显示数据曲线 ## 一、简介 ### 1. HA 配置文件 `configuration.yaml` 通过配置该文件对 HA 指定任务,HA 则根据该文件调用组件并实现目标。 该文件的设定修改步骤如下: 1. [设置文件访问权限](https://www.home-assistant.io/docs/configuration/#to-set-up-access-to-the-files-and-prepare-an-editor) 2. [找到 config 目录](https://www.home-assistant.io/docs/configuration/#to-find-the-configuration-directory) 3. 编辑 `configuration.yaml` 4. 保存更改并[重新加载配置](https://www.home-assistant.io/docs/configuration/#reloading-the-configuration-to-apply-changes)以应用更改 详见:[Configuration.yaml - Home Assistant (home-assistant.io)](https://www.home-assistant.io/docs/configuration/) . ### 2. MQTT JSON [JSON](https://www.json.org/json-zh.html), ( JavaScript Object Notation ), 是一种轻量级数据交换格式,如下 ```json { "some_arbitrary_key_name": "value" } ``` 详见:[MQTT JSON - Home Assistant (home-assistant.io)](https://www.home-assistant.io/integrations/mqtt_json/) . ## 二、方案 ### 1. 流程 将前面介绍的 SHT40 温湿度传感器的串口输出相关代码与开发板通过 MQTT 协议连接至 Home Assistant 平台的代码相结合,具体流程如下 1. 开发板读取 SHT40 传感器采集的环境温湿度数据 2. 数据通过 MQTT 协议上传至 EMQX 服务器 3. HA 平台订阅主题、读取数据并将其转化至可视化面板显示出来,并实现历史曲线的观测和记录。 ### 2. 代码 ``` #include
#if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_AVR_UNO_WIFI_REV2) #include
#elif defined(ARDUINO_SAMD_MKR1000) #include
#elif defined(ARDUINO_ARCH_ESP8266) #include
#elif defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA) #include
#elif defined(ARDUINO_PORTENTA_C33) #include
#elif defined(ARDUINO_UNOR4_WIFI) #include
#endif #include "Adafruit_SHT4x.h" #include "arduino_secrets.h" //please enter your sensitive data in the Secret tab/arduino_secrets.h char ssid[] = SECRET_SSID; // your network SSID (name) char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) // To connect with SSL/TLS: // 1) Change WiFiClient to WiFiSSLClient. // 2) Change port value from 1883 to 8883. // 3) Change broker value to a server with a known SSL/TLS root certificate // flashed in the WiFi module. WiFiClient wifiClient; MqttClient mqttClient(wifiClient); const char broker[] = "49.52.23.140"; // IP address int port = 1883; // port const char topic[] = "UNOR4/Send"; // MQTT topic const long interval = 1000; unsigned long previousMillis = 0; int count = 0; Adafruit_SHT4x sht4 = Adafruit_SHT4x(); float temperature_date,humidity_date; sensors_event_t humidity, temp; static TwoWire& SHT_I2C_INTERFACE = Wire1; // Wire1 is the QWIIC port of Uno R4 board void setup() { //Initialize serial and wait for port to open: Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.println("SHT40 test"); if (! sht4.begin(&SHT_I2C_INTERFACE)) { Serial.println("Couldn't find SHT40"); while (1) delay(1); } Serial.println("Found SHT40 sensor"); Serial.print("Serial number 0x"); Serial.println(sht4.readSerial(), HEX); // You can have 3 different precisions, higher precision takes longer sht4.setPrecision(SHT4X_HIGH_PRECISION); switch (sht4.getPrecision()) { case SHT4X_HIGH_PRECISION: Serial.println("High precision"); break; case SHT4X_MED_PRECISION: Serial.println("Med precision"); break; case SHT4X_LOW_PRECISION: Serial.println("Low precision"); break; } // You can have 6 different heater settings // higher heat and longer times uses more power // and reads will take longer too! sht4.setHeater(SHT4X_NO_HEATER); switch (sht4.getHeater()) { case SHT4X_NO_HEATER: Serial.println("No heater"); break; case SHT4X_HIGH_HEATER_1S: Serial.println("High heat for 1 second"); break; case SHT4X_HIGH_HEATER_100MS: Serial.println("High heat for 0.1 second"); break; case SHT4X_MED_HEATER_1S: Serial.println("Medium heat for 1 second"); break; case SHT4X_MED_HEATER_100MS: Serial.println("Medium heat for 0.1 second"); break; case SHT4X_LOW_HEATER_1S: Serial.println("Low heat for 1 second"); break; case SHT4X_LOW_HEATER_100MS: Serial.println("Low heat for 0.1 second"); break; } // attempt to connect to WiFi network: Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); while (WiFi.begin(ssid, pass) != WL_CONNECTED) { // failed, retry Serial.print("."); delay(5000); } Serial.println("You're connected to the network"); Serial.println(); Serial.println(WiFi.localIP()); // You can provide a unique client ID, if not set the library uses Arduino-millis() // Each client must have a unique client ID // mqttClient.setId("clientId"); // You can provide a username and password for authentication mqttClient.setUsernamePassword("UNOR4", "123456"); Serial.print("Attempting to connect to the MQTT broker: "); Serial.println(broker); if (!mqttClient.connect(broker, port)) { Serial.print("MQTT connection failed! Error code = "); Serial.println(mqttClient.connectError()); while (1); } Serial.println("You're connected to the MQTT broker!"); Serial.println(); } void loop() { // call poll() regularly to allow the library to send MQTT keep alives which // avoids being disconnected by the broker mqttClient.poll(); // to avoid having delays in loop, we'll use the strategy from BlinkWithoutDelay // see: File -> Examples -> 02.Digital -> BlinkWithoutDelay for more info unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { // save the last time a message was sent previousMillis = currentMillis; Serial.print("Sending message to topic: "); Serial.println(topic); // Serial.print("temperature:"); // Serial.println(temperature_date); // Serial.print("humidity: "); // Serial.println(humidity_date); uint32_t timestamp = millis(); sht4.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data timestamp = millis() - timestamp; Serial.print("Temperature: "); Serial.print(temp.temperature); Serial.println(" degrees C"); Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH"); Serial.print("Read duration (ms): "); Serial.println(timestamp); temperature_date=temp.temperature; humidity_date=humidity.relative_humidity; // send message, the Print interface can be used to set the message contents mqttClient.beginMessage(topic); mqttClient.println("{"); mqttClient.print(" \"temperature\":"); mqttClient.print(temperature_date); mqttClient.println(","); mqttClient.print(" \"humidity\":"); mqttClient.println(humidity_date); mqttClient.print("}"); mqttClient.endMessage(); Serial.println(); count+=0.01; } } ``` 串口输出情况如下
MQTTX 客户端输出效果如下
下面考虑如何将该数据显示在 HA 面板。 ### 3. MQTT 配置信息 前面测试程序中发送的是温度和湿度数据,因此需要在 Home Assistant 中增加传感器信息。 ```json # Example configuration.yaml entry mqtt: sensor: - name: "Temperature" state_topic: "UNOR4/Send" suggested_display_precision: 1 unit_of_measurement: "°C" value_template: "{{ value_json.temperature }}" - name: "Humidity" state_topic: "UNOR4/Send" unit_of_measurement: "%" value_template: "{{ value_json.humidity }}" ``` 参考: [MQTT Sensor - Home Assistant (home-assistant.io)](https://www.home-assistant.io/integrations/sensor.mqtt/) .
注意这里 HA 官方说明文档中给出的例程,其中开发板上传的数据格式为 JSON 格式,我们的输出结果与例程的格式一致,因此将例程中对应的 HA 配置代码添加至 `configuration.yaml` 文件并修改订阅主题即可。 ### 4. 效果 在 `设置` 中重新加载 `YAML 配置` 即可显示传感器面板及温湿度数据,如下图所示
点击 `Humidity` 和 `Temperature` 即可显示历史曲线,鼠标指针可以显示每个时刻的具体数据
此外,还可以将数据联系至仪表表盘,实现 UI 界面优化,使产品设计更加人性化。 #### 视频展示
VID_20240926_183919-(online-video-cutter.com)
MCU 开发者和爱好者
点赞
回复评论
暂无评论,赶紧抢沙发吧
最新活动
免费申请 | 上百份MPS MIE模块,免费试用还有礼!
TI 有奖直播 | 使用基于 Arm 的 AM6xA 处理器设计智能化楼宇
Follow me第二季第3期来啦!与得捷一起解锁高性能开发板【EK-RA6M5】超能力!
报名直播赢【双肩包、京东卡、水杯】| 高可靠性IGBT的新选择——安世半导体650V IGBT
30套RV1106 Linux开发板(带摄像头),邀您动手挑战边缘AI~
安世半导体理想二极管与负载开关,保障物联网应用的稳健高效运行
随便看看
JTAG 模式不能下载,BSL 模式同步错误!求助!!
关于51单片机状态周期中各拍的作用
陶老师的雷电防护以及ESD、EMI、EMC设计
自己制作蓝牙开发板,怎样进入调试模式?
大家各显身手
RLS波束形成算法在相干干扰环境中的应用
车载电子典型防反接电路分析
咨询就业
急求:信号发生器
stm8函数库
基准电压源参数initial accuracy
为什么一个简单的申请内存和释放存储出现错误!郁闷!
第一次用3DMAX,画了一支鼓棒
TMS570LS3137的RAMECC初始化
TMS320F28035学习记录
趣味电子技术史话栏目开播啦!第一集:白炽灯到底是谁发明的?
英飞凌简介
聘:产品检测人员(质检) 工作地点:成都
linux ccs
关于2407 仿真时load程序的问题
电子工程世界版权所有
京B2-20211791
京ICP备10001474号-1
京公网安备 11010802033920号
回复
写回复
收藏
回复