『瀚思彼岸』» 智能家居技术论坛

 找回密码
 立即注册
查看: 501|回复: 4

[技术探讨] 求教:8266 For Mqtt 代码

[复制链接]

4

主题

13

帖子

84

积分

注册会员

Rank: 2

积分
84
金钱
71
HASS币
0
发表于 2023-9-10 11:03:26 | 显示全部楼层 |阅读模式
小白我借助例程试着编译个小程序,用ESP8266向HA的Mqtt发送温湿度数据,数据倒是送到HA里面了,但是因为自己一知半解,程序输出串口监测没问题,但不能向mqtt成功发送浮点值,只能把值定义为整数(int)才能正确显示,但我想精确到小数点后面一位数,反复试了一晚上,C++基础太差搞不定啊!只能请教请教论坛的大佬们,不胜感激!用的传感器是SHT31。

截屏2023-09-10 09.23.37.png


#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ubSubClient.h>
#include <Wire.h>
#include "Adafruit_SHT31.h"

bool enableHeater = false;
uint8_t loopCnt = 0;

Adafruit_SHT31 sht31 = Adafruit_SHT31();


// Update these with values suitable for your network.
const char* ssid = "RickyHome2.4GHz";
const char* password = "12345678";
const char* mqtt_server = "172.18.8.6";
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
//C++11引入了Raw字符串,不用以上的转义斜杠,换行也不用斜杠,只要用R"()"包起来,方便写代码了
  char temperature[] = R"({
   "device_class": "temperature",
   "name": "outdoor_Temperature",
   "state_topic": "homeassistant/sensor/outdoor/state",
   "unit8_of_measurement": "°C","value_template": "{{ value_json.temperature}}"})";

  char Humidity[] = R"({
   "device_class": "humidity",
   "name": "outdoor_Humidity",
   "state_topic": "homeassistant/sensor/outdoor/state",
   "unit8_of_measurement": "%",
   "value_template": "{{ value_json.humidity}}"})";

  char Text[] = R"({
   "device_class": "TEXT",
   "name": "outdoor_TEXT",
   "state_topic": "homeassistant/sensor/outdoor/state",
   "value_template": "{{ value_json.humidity}}"})";

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
      if(client.connect("homeassistant/sensor/", "mqtt", "12345678"))//clientID, userName, userPassword
      {
      client.publish("homeassistant/sensor/outdoor_H/config", Humidity);
      client.publish("homeassistant/sensor/outdoor_T/config", temperature);
      client.publish("homeassistant/sensor/outdoor_TEXT/config", "text");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(20000);
    }
  }
}

void sht31_read() {

  float temperature = sht31.readTemperature();
  float humidity = sht31.readHumidity();

  Serial.print("H:");
  Serial.print(humidity);
  Serial.println(" %RH");
  Serial.print("C:");
  Serial.print(temperature);
  Serial.println("°C");


  Serial.print((int)temperature);
  Serial.print("°C");
  Serial.print((int)humidity);
  Serial.println("%RH");

  char msg[100];
  sprintf(msg,"{\"temperature\":%d, \"humidity\":%d}",(int)temperature,(int)humidity);
  client.publish("homeassistant/sensor/outdoor/state", msg);
  // sht31 sampling rate is 1HZ.
  return ;
}



void setup() {

Serial.begin(9600);

setup_wifi();

client.setServer(mqtt_server, 1883);

if (!client.connected()) {
    reconnect();
  }
  {
  //SHT31
  while (!Serial)
    delay(500);     // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("SHT31 Sensor");
  if (! sht31.begin(0x44)) {   // Set to 0x45 for alternate i2c addr
    Serial.println("Couldn't find SHT31");
   while (1) delay(1);  }

  Serial.print("Heater Enabled State: ");
  if (sht31.isHeaterEnabled())
    Serial.println("ENABLED");
  else
    Serial.println("DISABLED");}

}



unsigned long lastMsg = 0;
int value = 1;
void loop() {
  if (!client.connected()) {reconnect();}
  client.loop();
  unsigned long now = millis();
  if (now - lastMsg > 60000) {
    lastMsg = now;
    ++value;
    sht31_read();
  }
}

截屏2023-09-09 23.48.28.png
回复

使用道具 举报

2

主题

113

帖子

1194

积分

金牌会员

Rank: 6Rank: 6

积分
1194
金钱
1081
HASS币
0
发表于 2023-9-10 14:02:11 来自手机 | 显示全部楼层

回帖奖励 +20 金钱

为啥不用esphome
回复

使用道具 举报

11

主题

287

帖子

2027

积分

金牌会员

Rank: 6Rank: 6

积分
2027
金钱
1740
HASS币
0
发表于 2023-9-10 16:16:53 | 显示全部楼层

回帖奖励 +20 金钱

为啥不用Tasmota  我也來賺個獎勵
回复

使用道具 举报

16

主题

203

帖子

1592

积分

论坛DIY达人

积分
1592
金钱
1384
HASS币
20
发表于 2023-9-10 22:05:53 | 显示全部楼层
本帖最后由 polisher 于 2023-9-10 22:10 编辑

从您提供的代码上发现一点问题。
sprintf(msg,"{\"temperature\":%d, \"humidity\":%d}",(int)temperature,(int)humidity);
可能问题出在您使用了(int)对浮点数进行了取整运算,您可尝试将以下代码:sprintf(msg,"{\"temperature\":%f, \"humidity\":%f}",temperature,humidity);
猜想您是在Arduino下编写的吧,不是很懂,仅供参考。
另,您如果只是用于HA,干嘛不直接用esphome呢?

评分

参与人数 1金钱 +2 收起 理由
rickyshen + 2 感谢!新手只有这么多了!

查看全部评分

回复

使用道具 举报

4

主题

13

帖子

84

积分

注册会员

Rank: 2

积分
84
金钱
71
HASS币
0
 楼主| 发表于 2023-9-11 10:43:47 | 显示全部楼层
本帖最后由 rickyshen 于 2023-9-11 10:46 编辑
polisher 发表于 2023-9-10 22:05
从您提供的代码上发现一点问题。
sprintf(msg,"{\"temperature\":%d, \"humidity\":%d}",(int)temperature, ...

感谢感谢!我根据您的指点修改后果然好了!!!!哎!之前把1f加到()里,新手不懂语法。
sprintf(msg, "{\"temperature\":%.1f, \"humidity\":%.1f}", temperature, humidity);
截屏2023-09-11 10.33.43.png
另外因为我某个knx显示面板一行只能接收一个值,但我想让它同时显示温湿度甚至pm2.5,所以我想给它发字符串。
实现将数值赋予到一段字符串中,比如:Outdoor 28.3°C 70%RH,请教用sprintf发送到mqtt的话该如何写?
ESPHOME我刚才试了,居然调不出sht3xd库(DHT可以),我现在下了个DEV版本看看
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-4-28 20:18 , Processed in 0.151217 second(s), 30 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表