请选择 进入手机版 | 继续访问电脑版

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

 找回密码
 立即注册
查看: 6831|回复: 9

mqtt 局域网 esp8266 温湿度传感器代码

[复制链接]

8

主题

73

帖子

693

积分

高级会员

Rank: 4

积分
693
金钱
620
HASS币
30
发表于 2020-12-21 19:47:59 | 显示全部楼层 |阅读模式
esp8266 温湿度传感器代码,esp-01s +dht11,具体代码如下:


#include <WiFi.h>
#include <PubSubClient.h>  
#include <DHT.h>

//设置wifi账号密码以及mqtt服务器地址,mqtt服务器默认端口1883
const char* ssid = "****";
const char* password = "*******";
const char* mqtt_server = "192.168.1.4";
//设置esp32 dht11温湿度传感器针脚地址
#define DHTPIN 4
//定义使用传感器型号
#define DHTTYPE DHT11   // DHT 11

//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

//#define DHTTYPE DHT21   // DHT 21 (AM2301)
//设置wifi参数给mqtt
WiFiClient espClient;
PubSubClient client(espClient);
//设置mqtt消息变量
char msg[50];
//板载led引脚
int ledpin=11;
int temp;//温度
int humi;//湿度
//配置dht传感器类型及引脚
DHT dht(DHTPIN, DHTTYPE);
//初始化时间计数
uint32_t read_time = 0;

void setup()
{

    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
    pinMode(ledpin, OUTPUT);
    digitalWrite(ledpin, LOW);
    dht.begin();

}



void loop()

{
//检查mqtt链接是否正常
  if (!client.connected()) {
    reconnect();
  }
  client.loop();    //检查调用回调函数
  //延迟采集设置,目前延迟时间为2000毫秒
  if (read_time == 0 || (millis() - read_time) >= 2000)
  {
      read_time = millis();
      float h = dht.readHumidity();          //读取湿度
      float t = dht.readTemperature();        //读取温度
      if (isnan(h) || isnan(t)) {             //判断温湿度值是否正常,不正常则跳出循环
          return;
      }
      float hic = dht.computeHeatIndex(t, h, false);
      humi = h;
      temp = t;
      snprintf (msg, 75, "{\"datetime\":\"2018-7-2 20:30\",\"temp\":%ld,\"humi\":%ld}", temp,humi);
      Serial.print("Publish message: ");
      Serial.println(msg);
      client.publish("hmdata", msg);
  }
}
//链接wifi函数
void setup_wifi() {     
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

//mqtt回调函数
void callback(char* topic, byte* payload, unsigned int length) {    //回调函数
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  // Switch on the LED if an 1 was received as first character
  if (length>2){
    if ((char)payload[length-2] == '1') {
      digitalWrite(ledpin, LOW);   // Turn the LED on (Note that LOW is the voltage level
      // but actually the LED is on; this is because
      // it is acive low on the ESP-01)
    } else {
      digitalWrite(ledpin, HIGH);  // Turn the LED off by making the voltage HIGH
    }
  }
}


void reconnect() {        //每次发布mqtt信息时,需检查链接
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ID_ESP32Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("hmdata", "{\"datetime\":\"2018-7-1 19:30\",\"temp\":25,\"humi\":100}");  //发布json格式
      // ... and resubscribe
      client.subscribe("hmdata");        //订阅
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}



上面代码复制,新建文件保存为.ino文件或者直接复制到mixly里下载到esp-01s。
hass的configuration配置如下:
# 温度传感器
sensor 1:
  platform: mqtt
  name: "temperature"
  state_topic: "hmdata"
  unit_of_measurement: "°C"
  value_template: "{{value_json.temp}}"

# 湿度传感器
sensor 2:
  platform: mqtt
  name: "humidity"
  state_topic: "hmdata"
  unit_of_measurement: "%"
  value_template: "{{value_json.humi}}"


保存重启
回复

使用道具 举报

9

主题

518

帖子

2275

积分

金牌会员

Rank: 6Rank: 6

积分
2275
金钱
1757
HASS币
0
发表于 2020-12-21 21:12:46 | 显示全部楼层
arduino?
还是esphome
回复

使用道具 举报

8

主题

73

帖子

693

积分

高级会员

Rank: 4

积分
693
金钱
620
HASS币
30
 楼主| 发表于 2021-1-8 21:42:45 | 显示全部楼层
yylwhy 发表于 2020-12-21 21:12
arduino?
还是esphome

arduino的代码,esphome我觉得没有自己写的好,自己可以随意定制
回复

使用道具 举报

3

主题

26

帖子

334

积分

中级会员

Rank: 3Rank: 3

积分
334
金钱
308
HASS币
0
发表于 2021-2-26 09:31:50 | 显示全部楼层
学习下,自己定制Esp8266通过mqtt接入HA
回复

使用道具 举报

0

主题

37

帖子

333

积分

中级会员

Rank: 3Rank: 3

积分
333
金钱
296
HASS币
0
发表于 2021-3-1 20:34:33 | 显示全部楼层
先收藏着,等设备到
回复

使用道具 举报

1

主题

9

帖子

156

积分

注册会员

Rank: 2

积分
156
金钱
147
HASS币
0
发表于 2021-3-17 17:49:09 来自手机 | 显示全部楼层
小白正好入了这两个硬件,Mark了学习实践一下
回复

使用道具 举报

1

主题

38

帖子

418

积分

中级会员

Rank: 3Rank: 3

积分
418
金钱
380
HASS币
0
发表于 2021-6-27 18:50:05 | 显示全部楼层
正在学这个,谢谢
回复

使用道具 举报

1

主题

38

帖子

418

积分

中级会员

Rank: 3Rank: 3

积分
418
金钱
380
HASS币
0
发表于 2021-6-28 08:32:15 | 显示全部楼层
如果我8266部分直接使用esphome来连接mqtt服务器该怎么写呢,主要是贪图esphome里面ota方便。
回复

使用道具 举报

8

主题

73

帖子

693

积分

高级会员

Rank: 4

积分
693
金钱
620
HASS币
30
 楼主| 发表于 2021-7-23 22:04:56 | 显示全部楼层
yibamao 发表于 2021-6-28 08:32
如果我8266部分直接使用esphome来连接mqtt服务器该怎么写呢,主要是贪图esphome里面ota方便。 ...

不建议用。。。可定制性太差
回复

使用道具 举报

2

主题

68

帖子

379

积分

中级会员

Rank: 3Rank: 3

积分
379
金钱
311
HASS币
0
发表于 2022-3-16 22:22:31 | 显示全部楼层
能否来个 视频教程啊,一穷二白啊,不知道 怎么搞
回复

使用道具 举报

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

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-3-29 00:14 , Processed in 0.052622 second(s), 31 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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