【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");
}
|