Follow me Season 2 Episode 2 + Extended Task 2: Upload HA and display it through an external SHT40 temperature and humidity sensor
[Copy link]
Through the external SHT40 temperature and humidity sensor, the temperature and humidity data are uploaded to Home Assistant (HA) and displayed on the HA panel.
1. Preparation
Connect SHT40 temperature and humidity sensor
Use 4885 (SHT40 temperature and humidity sensor expansion board) to connect the SHT40 temperature and humidity sensor with Arduino UNO R4 WiFi.
The SHT40 sensor usually has four pins: VCC, GND, SCK (clock line) and SDA (data line), which are correctly connected to the expansion board and Arduino J2.
In the Arduino IDE, search for and install the Adafruit_SHT4x library through the library manager. This library provides the functions and interfaces needed to communicate with the SHT40 sensor.
Programming the Arduino
Initialize the WiFi connection, and configure the MQTT client to connect to HA's MQTT server.
Use the Adafruit_SHT4x library to read temperature and humidity data.
The read temperature and humidity data are serialized into JSON format and sent to HA via the MQTT protocol.
2. Code:
#include "Adafruit_SHT4x.h" // 引入Adafruit SHT4x库
#include <ArduinoMqttClient.h> // 引入Arduino MQTT客户端库
#include <WiFiS3.h> // 引入WiFi库(适用于ESP32)
#include <WiFiClient.h> // 引入WiFi客户端库
#include <Arduino_JSON.h> // 引入Arduino JSON库
Adafruit_SHT4x sht4; // 创建SHT4x对象
char ssid[] = "CMCC-c6tG"; // WiFi网络的SSID
char pass[] = "mei13728232960"; // WiFi网络的密码
int status = WL_IDLE_STATUS; // WiFi连接状态
const char broker[] = "192.168.1.113"; // MQTT代理的IP地址
int port = 1883; // MQTT代理的端口号
const char command_topic[] = "office/sensor1"; // MQTT主题
WiFiClient wifiClient; // 创建WiFi客户端对象
MqttClient mqttClient(wifiClient); // 创建MQTT客户端对象
JSONVar dataObj; // 创建JSON对象用于存储数据
void setup() {
Serial.begin(115200); // 初始化串口通信
// 设置SHT4x的精度为高精度
sht4.setPrecision(SHT4X_HIGH_PRECISION);
// 打印当前设置的精度
switch (sht4.getPrecision()) {
case SHT4X_HIGH_PRECISION:
Serial.println(F("SHT40 set to High precision"));
break;
case SHT4X_MED_PRECISION:
Serial.println(F("SHT40 set to Medium precision"));
break;
case SHT4X_LOW_PRECISION:
Serial.println(F("SHT40 set to Low precision"));
break;
}
// 关闭SHT4x的加热器
sht4.setHeater(SHT4X_NO_HEATER);
// 打印当前加热器的状态
switch (sht4.getHeater()) {
case SHT4X_NO_HEATER:
Serial.println(F("SHT40 Heater turned OFF"));
break;
// 其他加热器状态...
}
// 初始化SHT4x传感器
if (!sht4.begin(&Wire1)) {
Serial.println(F("SHT40 sensor not found!"));
while (1); // 如果传感器未找到,则停止程序
} else {
Serial.print(F("SHT40 detected!\t"));
Serial.print(F("Serial number:\t"));
Serial.println(sht4.readSerial(), HEX); // 打印传感器的序列号
}
Serial.println(F("----------------------------------"));
// 检查WiFi固件版本
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
// 连接到WiFi网络
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(10000); // 等待10秒尝试连接
}
Serial.print("You're connected to the network");
printCurrentNet(); // 打印当前网络的信息
printWifiData(); // 打印WiFi数据
// 连接到MQTT代理
if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());
while (1); // 如果连接失败,则停止程序
}
Serial.println("You are connected to MQTT");
// 检查WiFi模块是否通信正常
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
while (true); // 如果通信失败,则停止程序
}
}
// 打印当前网络的信息
void printCurrentNet() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
printMacAddress(bssid);
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption, HEX);
Serial.println();
}
// 打印MAC地址
void printMacAddress(byte mac[]) {
for (int i = 0; i < 6; i++) {
if (i > 0) {
Serial.print(":");
}
if (mac[i] < 16) {
Serial.print("0");
}
Serial.print(mac[i], HEX);
}
Serial.println();
}
// 打印WiFi数据
void printWifiData() {
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
printMacAddress(mac);
}
void loop() {
sensors_event_t humidity, temp; // 创建用于存储温度和湿度数据的结构体
sht4.getEvent(&humidity, &temp); // 从传感器获取最新的温度和湿度数据
float t = temp.temperature; // 获取温度值
Serial.println("Temp *C = " + String(t)); // 打印温度值
float h = humidity.relative_humidity; // 获取湿度值
Serial.println("Hum. % = " + String(h)); // 打印湿度值
// 将温度和湿度数据添加到JSON对象中
dataObj["temperature"] = t;
dataObj["humidity"] = h;
// 将JSON对象转换为字符串
String jsonString = JSON.stringify(dataObj);
// 通过MQTT发送数据
mqttClient.beginMessage(command_topic);
mqttClient.print(jsonString);
mqttClient.endMessage();
delay(500); // 等待500毫秒后再次读取数据
}
Code explanation:
Added library files
Adafruit_SHT4x.h: used to interact with Adafruit SHT4x temperature and humidity sensors.
ArduinoMqttClient.h: used to implement MQTT communication.
WiFiS3.h and WiFiClient.h: used to connect to WiFi networks.
Arduino_JSON.h: used to process JSON data.
Define variables and objects
Adafruit_SHT4x sht4: Create SHT4x temperature and humidity sensor object.
char ssid[] and char pass[]: Store the name and password of the WiFi network.
int status: Used to store the WiFi connection status.
const char broker[] and int port: The address and port of the MQTT server.
const char command_topic[]: The topic of MQTT.
WiFiClient wifiClient and MqttClient mqttClient(wifiClient): Create WiFi client and MQTT client objects.
JSONVar dataObj: Used to store the JSON data to be sent.
setup function
Initialize serial communication and set the baud rate to 115200.
Set the accuracy of the SHT4x sensor to high accuracy and print the current accuracy.
Turn off the heater of the SHT4x sensor and print the current heater status.
Initialize the SHT4x sensor. If the sensor is not found, enter an infinite loop. If the sensor is found, print whether the sensor is detected and the serial number of the sensor.
Check the WiFi firmware version. If it is not the latest version, prompt to upgrade.
Try to connect to the specified WiFi network until the connection is successful.
Connect to the MQTT server. If the connection fails, print the error message and enter an infinite loop.
Check the WiFi module status. If the communication fails, enter an infinite loop.
printCurrentNet function
Prints the SSID of the currently connected WiFi network.
Prints the MAC address of the currently connected router.
Prints the received signal strength (RSSI).
Prints the encryption type.
printMacAddress function
Iterates through the passed MAC address array, converts each byte into hexadecimal format and prints it, separating them with colons.
printWifiData function
Print the IP address of the development board.
Print the MAC address of the development board by calling the printMacAddress function.
loop function
Creates the structure sensors_event_t humidity, temp for storing temperature and humidity data.
Gets the latest temperature and humidity data from the sensor.
Gets the temperature and humidity values and prints them out.
Adds the temperature and humidity data to dataObj, converts it to a JSON string, and sends it to the specified topic through the MQTT client.
Reads the data again after a delay of 500 milliseconds.
3. Achievement Effect
|