307|0

5

帖子

1

TA的资源

一粒金砂(中级)

楼主
 

【Follow me第二季第2期】 扩展任务二:通过外部SHT40温湿度传感器,上传温湿度到H... [复制链接]

  本帖最后由 eew_HqZm7h 于 2024-10-8 13:41 编辑

任务步骤:

1.单片机接收传感器数据并打印

2.将数据通过MQTT协议传输到Home Assistant上

 

1.单片机接收传感器数据并打印

(1)下载“SHT4x”库,使用SHT4test样例测试传感器传输数据到单片机

 

/*************************************************** 
  This is an example for the SHT4x Humidity & Temp Sensor

  Designed specifically to work with the SHT4x sensor from Adafruit
  ----> https://www.adafruit.com/products/4885

  These sensors use I2C to communicate, 2 pins are required to  
  interface
 ****************************************************/

#include "Adafruit_SHT4x.h"

Adafruit_SHT4x sht4 = Adafruit_SHT4x();

void setup() {
  Serial.begin(115200);

  while (!Serial)
    delay(10);     // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("Adafruit SHT4x test");
  if (! sht4.begin()) {
    Serial.println("Couldn't find SHT4x");
    while (1) delay(1);
  }
  Serial.println("Found SHT4x 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;
  }
  
}


void loop() {
  sensors_event_t humidity, temp;
  
  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);

  delay(1000);
}

测试结果:

 

2.将数据通过MQTT协议传输到Home Assistant上

(1)在Home Assistant上创建传感器主题(各个参数的信息可以在MQTT Sensor查看)

点击“配置”,发送数据包,创建传感器

(2)发送数据包创建传感器数据(通过监听测试发送是否成功)

 

homeassistant/sensor/SHT40_HUMI/config //创建湿度数据
{
    "device_class":"humidity",
    "name":"Humidity",
    "state_topic":"homeassistant/SHT40/state",
    "unit_of_measurement":"rH%",
    "value_template":"{{ value_json.humidity}}",
    "unique_id":"hum_HA101",
    "device":{
        "identifiers":[
            "SHT40"
        ],
        "name":"SHT40-HUMI_HUMI"
    }
}

 

homeassistant/sensor/SHT40_TEMP/config //创建温度数据

{
    "device_class":"temperature",
    "name":"Temperature",
    "state_topic":"homeassistant/SHT40/state",
    "unit_of_measurement":"°C",
    "value_template":"{{ value_json.temperature}}",
    "unique_id":"temp_HA101",
    "device":{
        "identifiers":[
            "SHT40"
        ],
        "name":"SHT40-TEMP_TEMP"
    }
}

测试结果:得到接收湿度数据和温度数据的主体

  

(3)单片机将传感器的数据传输到HomeAssistant中

/*

  This example connects to a MQTT broker and publishes a message to
  a topic once a second.

  The circuit:
  - Arduino MKR 1000, MKR 1010 or Uno WiFi Rev2 board

  This example code is in the public domain.
*/

#include <ArduinoMqttClient.h>
#include <WiFiS3.h>
#include "Adafruit_SHT4x.h"
Adafruit_SHT4x sht4 = Adafruit_SHT4x();

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "一觉睡到日三竿";    // your network SSID (name)
char pass[] = "chen2456594826";    // 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[] = "192.168.187.230";
int        port     = 1883;
const char topic[]  = "homeassistant/SHT40/state";

const long interval = 1000;
unsigned long previousMillis = 0;

int count = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // 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(ssid);
  printWifiStatus();
  Serial.println();

  // 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("clientIdmurong");

  // You can provide a username and password for authentication
//   mqttClient.setUsernamePassword("arduinoUnoBoard", "arduinoUnoBoard");
  mqttClient.setUsernamePassword("admin", "20030121chen");

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

#if 0
  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }
#endif

while (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());
    delay(100);
  }


  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

  //Following are SHT4x Test
  Serial.println("Adafruit SHT4x Init");
  if (! sht4.begin()) {
    Serial.println("Couldn't find SHT4x");
    while (1) delay(1);
  }
  Serial.println("Found SHT4x 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;
  }

}

void loop() {
  sensors_event_t humidity, temp;
  sht4.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data

  // 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.println(count);

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(topic);
    mqttClient.print("{\"humidity\": ");
    mqttClient.print(humidity.relative_humidity);
    mqttClient.print(", \"temperature\": ");
    mqttClient.print(temp.temperature);
    mqttClient.print("}");
    mqttClient.endMessage();

    Serial.println();

    count++;
  }
}

/* -------------------------------------------------------------------------- */
void printWifiStatus() {
/* -------------------------------------------------------------------------- */  
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

 

 

点赞 关注
 
 

回复
举报
您需要登录后才可以回帖 登录 | 注册

随便看看
查找数据手册?

EEWorld Datasheet 技术支持

相关文章 更多>>
推荐帖子
四大品牌无线路由器产品推荐

来源:中关村在线 无线市场上最为人熟知的绝对是TP-Link、D-Link、网件、 Linksys四大品牌。如果您说买东西光看品牌是傻子,我 ...

芯片封装概述

芯片封装 一、DIP双列直插式封装  DIP(DualIn-line Package)是指采用双列直插形式封装的集成电路芯片,绝大多数中小规模 ...

IC设计工程师的高手进阶之路

随着中国IC设计产业渐入佳境,越来越多的工程师加入到这个新兴产业中。从一个初学者成长到主持大型设计的IC设计专家,这是每个IC ...

Helper2416-13——裸机第五弹——YL-boot——裸奔者的福音

YL-boot——裸奔者的福音 参与Helper2416开发板助学计划心得 闭关几天,终于初步完成了这YL-boot了。没有J-TAG不能单步调试还 ...

#8月改装#暴力改装普源DP832电源

本帖最后由 wangjiafu1985 于 2015-8-27 09:04 编辑 暴力改装普源DP832电源  免责声明:本贴发表之前经SOSO姐向普源提出授 ...

2020年1月份版主工作奖励

2020年1月获得版主奖励的名单如下: 用户名 发帖 回帖 加精 评分次数 删除主题/ ...

视频动画:直观的理解电磁波辐射

attach://480168.qlv480168 视频动画:直观的理解电磁波辐射 480168

Teensy 4.1 开发板

480436 Teensy 4.1,相比Teensy 4.0 有了不少改进。 引脚图 连接以太网 反面可以扩展存储器,左边是p ...

FPGA入门必备《Advanced FPGA Design》

国外FPGA设计经典教材《Advanced FPGA Design:Architecture, Implementation, and Optimization》,适合入门初学者学习。 ...

请教一个电源变压器后面电路问题

请教一个电源变压器后面电路问题 二极管和电阻前后调换一下位置,有什么影响? 862533

关闭
站长推荐上一条 1/10 下一条

 
EEWorld订阅号

 
EEWorld服务号

 
汽车开发圈

About Us 关于我们 客户服务 联系方式 器件索引 网站地图 最新更新 手机版

站点相关: 国产芯 安防电子 汽车电子 手机便携 工业控制 家用电子 医疗电子 测试测量 网络通信 物联网

北京市海淀区中关村大街18号B座15层1530室 电话:(010)82350740 邮编:100190

电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号 Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved
快速回复 返回顶部 返回列表