[作品提交] 【Follow me第二季第2期】进阶任务+扩展任务二 之 将SHT40数据通过MQTT传输到HA平台

eew_Eu6WaC   2024-9-15 09:35 楼主

任务总览 

  1. 获取SHT40的温湿度数据
  2. 搭建HomeAssistant平台
  3. 将设备接入到HomeAssistant平台

1.获取SHT40的温湿度数据

先使用官方例程测试一下SHT40传感器

/*************************************************** 
  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 <Wire.h>
#include "Adafruit_SHT4x.h"

#define SDA_PIN 27
#define SCL_PIN 26


Adafruit_SHT4x sht4 = Adafruit_SHT4x();

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

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

  TwoWire i2cWire = TwoWire(SCL_PIN, SDA_PIN);
  
  Serial.println("Adafruit SHT4x test");
  if (! sht4.begin(&i2cWire)) {
    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);
}

串口打印出来的数据:

Adafruit SHT4x test
Found SHT4x sensor
Serial number 0x10C60BD0
High precision
No heater
Temperature: 30.67 degrees C
Humidity: 70.80% rH
Read duration (ms): 11

2. 搭建HomeAssistant平台

1. SD卡格式化

推荐使用SDFormatter(内存卡修复工具),经常在Linux和Windwos下使用的SD卡通常会有着不同的分区,在不能操作系统下识别出来的可能都不太一样,因此为了保险起见可以先格式化一下,若没有问题的可以跳过这一步

SD卡格式化工具.png

 

2. SD卡烧写镜像工具

推荐使用balenaEtcher,这是一个开源的、跨平台的工具,用于将操作系统镜像文件(如 ISO 和 IMG 文件)烧录到 SD 卡和 USB 驱动器中,支持的格式非常的多

SD卡烧写镜像工具.png
  1. 选择镜像文件。我是用的是树莓派4,因此选择的是haos_rpi4-64-6.4.img.xz,大家根据自己的设备在附件中选择对应的型号即可。

  2. 选择SD卡、U盘等设备

  3. Flash!等待烧写完成

3. 上电!配置树莓派

  1. 插入烧写好的镜像SD卡到树莓派

  2. 接网线到路由器

  3. 将电脑通过WiFi或者网线接入到上面树莓派接入的路由器

  4. 接HDMI到显示屏等能够显示的设备(有条件的最后接上,没有问题也不是很大)

  5. 上电!

若插上HDMI,稍稍稍微的登上那么一段时间,等待系统启动完成就可以看到这个界面了,若没有显示屏,不要捉急,在网站上输入http://homeassistant.local:8123/等待网页显示。若成功启动了,恭喜你完成了第一步!!!

image-20240916085829663.png

能成功进入网站上,会显示这个界面准备,我一开始信了这个鬼(这最多可能需要20分钟),结果等了一个多小时都没有进去……

 

image-20240916090548199.png

第二天起来看到已经到了Home Assistant 的欢迎界面,按照步骤一步步下去就可以了

onboarding_preparing_01_.png
username.png
onboarding_location.png

 

onboarding_share_anonymized_info.png
onboarding_devices.png

点击FINISH之后,恭喜你现在已经启动并运行了 Home Assistant!!!

HA配置

SSH安装

  1. 设置

  2. 加载项

  3. 加载项商店

  4. 搜索ssh

image-20240916094432487.png

 

  1. 安装后

    image-20240916094455696.png

  2. 成功安装的界面:

image-20240916093844549.png

Samba 安装

  1. 设置

  2. 加载项

  3. 加载项商店

  4. 搜索Samba

image-20240916091726760.png

  1. 安装

    image-20240916091841411.png

     

  2. 配置:用户名和密码

  3. 使用:

    1. Win+R

    2. 输出\ip,例如\\192.168.1.43,这个ip就是上面ssh中查到的ip地址

    3. 就可以跟使用文件夹一样,对树莓派里面的文件进行操作了

安装MQTT

  1. 设置

  2. 加载项

  3. 加载项商店

  4. 搜索MQTT

image-20240916094746239.png
  1. 设置-》设备于服务-》打开MQTT-》配置,就可以了以下界面,进行配置ip,用户名、密码等信息,记住这些信息哟

image-20240916094934887.png
  1. 添加设备,使用的软件是MQTTx,发送下面数据,湿度同理

    {
    "name": "SHT40 Humidity",
    "state_topic": "homeassistant/sensor/sht40_humidity/state",
    "unit_of_measurement": "%rH",
    "device_class": "temperature",
    "json_attributes_topic": "homeassistant/sensor/sht40_humidity/attributes",
    "unique_id": "sht40_humidity",
    "device": {
      "identifiers": ["sht40"],
      "name": "SHT40 Sensor",
      "model": "SHT40",
      "manufacturer": "SHT"
    }
    }
    1. 就可以看到添加的设备了

    .

    image-20240916095240763.png
代码和效果展示
    
#include "Adafruit_SHT4x.h"

#define SDA_PIN 27
#define SCL_PIN 26

Adafruit_SHT4x sht4 = Adafruit_SHT4x();

#include <WiFi.h>
#include <ArduinoMqttClient.h>

char ssid[] = "wifi";  // your network SSID (name)
char pass[] = "passpword";  // your network password 

char mqtt_user[] = "master";
char mqtt_pass[] = "1";

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "192.168.1.22"; // MQTT broker address
int port = 1883;
const char subscribe_topic[] = "/status";
const char publish_topic_sht40_temperature[] = "homeassistant/sensor/sht40_temperature/state";
const char publish_topic_sht40_humidity[] = "homeassistant/sensor/sht40_humidity/state";

sensors_event_t humidity, temp;

void setup() {

	//打开串口
	Serial.begin(115200);

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

	//连接WIFI
	// Connect to WiFi
	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("\nYou're connected to the network");
	Serial.print("IP Address: ");
	Serial.println(WiFi.localIP());
	Serial.print("Gateway IP: ");
	Serial.println(WiFi.gatewayIP());
	Serial.print("Subnet Mask: ");
	Serial.println(WiFi.subnetMask());
	Serial.print("MAC Address: ");
	//Serial.println(WiFi.macAddress());
	Serial.println();

	//连接MQTT
	// Set MQTT username and password
	mqttClient.setUsernamePassword(mqtt_user, mqtt_pass);

	Serial.print("Attempting to connect to the MQTT 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.print("Subscribing to topic: ");
	Serial.println(subscribe_topic);

	// Subscribe to a topic
	mqttClient.subscribe(subscribe_topic);

	Serial.print("Waiting for messages on topic: ");
	Serial.println(subscribe_topic);


	//连接SHT40
	TwoWire i2cWire = TwoWire(SCL_PIN, SDA_PIN);

	Serial.println("SHT40 测试");
	if (! sht4.begin(&i2cWire)) {
	  Serial.println("无法访问SHT40");
	  while (1) delay(1);
	}
	Serial.println("开始读取SHT40序列号");
	Serial.print("SHT40的序列号是:");
	Serial.println(sht4.readSerial(), HEX);



	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);

}

void loop() {
	// put your main code here, to run repeatedly:

	uint32_t timestamp = millis();

	Serial.println("1");

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

	Serial.println("2");

	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);

	publishMessage_sht40_temperature(String(temp.temperature));
	publishMessage_sht40_humidity(String(humidity.relative_humidity));

}

// Function to publish a message to the MQTT broker
//发布温度信息
void publishMessage_sht40_temperature(const String &message) {
	mqttClient.beginMessage(publish_topic_sht40_temperature);
	mqttClient.print(message);
	mqttClient.endMessage();
}

// Function to publish a message to the MQTT broker
//发布湿度信息
void publishMessage_sht40_humidity(const String &message) {
	mqttClient.beginMessage(publish_topic_sht40_humidity);
	mqttClient.print(message);
	mqttClient.endMessage();
}

HomeAssistant

 

 

本帖最后由 eew_Eu6WaC 于 2024-9-16 10:11 编辑

回复评论

暂无评论,赶紧抢沙发吧
电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 京公网安备 11010802033920号
    写回复