数码之家

 找回密码
 立即注册

QQ登录

只需一步,快速开始

微信登录

微信扫一扫,快速登录

搜索
查看: 495|回复: 3

[Arduino] [esp32] dht11 MQTT

[复制链接]
发表于 2025-2-20 21:48:47 | 显示全部楼层 |阅读模式


Arduino软件和库是真的好用!!!

  1. #include "DHT.h"   // 包含DHT库
  2. #include <WiFi.h>
  3. #include <PubSubClient.h>
  4. #include <Arduino.h>
  5. #include <ArduinoJson.h>


  6. #define DHTPIN 14  // 定义DHT11数据引脚连接到ESP32的GPIO14
  7. #define DHTTYPE DHT11   // 定义传感器类型为DHT11


  8. #define MAX_RETRIES 20          // 网络最大连接次数
  9. #define MQTT_CALLBACK 1         // 是否开启MQTT回调函数

  10. const char* ssid="FAST_20CC";         // 网络信息
  11. const char* pass="409409409";

  12. // 设备标识
  13. const char *device_id = "esp32_001";

  14. // 设置MQTT borker信息
  15. const char *mqtt_broker = "192.168.1.111";  
  16. const char *topic = "espiot";
  17. const char *mqtt_username = "";
  18. const char *mqtt_password = "";
  19. const int mqtt_port = 1883;
  20. const char *client_id = "mqtt-client-esp3201";

  21. String heartBeatMsg;

  22. DHT dht(DHTPIN, DHTTYPE);  // 创建DHT传感器对象
  23. WiFiClient espClient;
  24. PubSubClient client(espClient);

  25. // MQTT监听函数
  26. void mqttCallback(char *topic, byte *payload, unsigned int length) {
  27.   Serial.print("Message arrived in topic: ");
  28.   Serial.println(topic);
  29.   Serial.print("Message:");
  30.   String charPayload;
  31.   for (int i = 0; i < length; i++) {
  32.     charPayload += (char) payload[i];
  33.   }
  34.   Serial.println(charPayload);
  35.   Serial.println("-----------------------");
  36. }

  37. // 网络连接函数
  38. bool connectWifi(){
  39.   Serial.println("调用WiFi连接函数");
  40.   WiFi.begin(ssid, pass);

  41.   for(int i=0; i<MAX_RETRIES; i++){
  42.     delay(500);
  43.     if(WiFi.status()==WL_CONNECTED){
  44.       Serial.println("网络连接成功");
  45.       return true;
  46.     }
  47.   }
  48.   if(WiFi.status()!=WL_CONNECTED){
  49.     Serial.println("网络连接超时");
  50.     return false;
  51.   }
  52. }

  53. // MQTT服务器连接函数
  54. bool connectMqtt(){
  55.   Serial.println("调用MQTT连接函数");
  56.   client.setServer(mqtt_broker, mqtt_port);

  57.   #if MQTT_CALLBACK
  58.   Serial.println("调用MQTT回调函数");
  59.   client.setCallback(mqttCallback);
  60.   #endif

  61.   if(WiFi.status()==WL_CONNECTED){
  62.     for(int i=0; i<MAX_RETRIES; i++){
  63.       delay(1000);
  64.       if(client.connect(client_id, mqtt_username, mqtt_password)){
  65.         Serial.println("MQTT服务器连接成功");
  66.         return true;
  67.       }
  68.     }
  69.     if(!client.connected()){
  70.       Serial.println("MQTT服务器连接超时");
  71.       return false;
  72.     }
  73.   }else{
  74.     Serial.println("网络连接失败");
  75.     return false;
  76.   }
  77. }

  78. //创建dht11的json数据
  79. String createDhtMsg(float temperature, float humidity) {
  80.   StaticJsonDocument<400> doc;
  81.   doc["source"] = device_id;
  82.   doc["target"] = "server";
  83.   doc["msgType"] = "temp-humi";
  84.   doc["temperature"] = temperature;
  85.   doc["humidity"] = humidity;


  86.   String jsonString;
  87.   serializeJson(doc, jsonString);
  88.   doc.clear();
  89.   return jsonString;
  90. }


  91. //创建心跳数据
  92. String createHeartBeatMsg(String ip) {
  93.   StaticJsonDocument<400> doc;
  94.   doc["source"] = device_id;
  95.   doc["target"] = "server";
  96.   doc["msgType"] = "heartbeat";
  97.   doc["ssid"] = ssid;
  98.   doc["ip"] = ip;

  99.   String jsonString;
  100.   serializeJson(doc, jsonString);
  101.   doc.clear();
  102.   return jsonString;
  103. }

  104. String ipToString(IPAddress ip) {
  105.   String result = "";
  106.   for (int i = 0; i < 4; i++) {
  107.     result += String(ip[i]);
  108.     if (i < 3) {
  109.       result += ".";
  110.     }
  111.   }
  112.   return result;
  113. }



  114. void setup() {
  115.   Serial.begin(9600);   // 初始化串口通信,波特率设置为9600
  116.   dht.begin();          // 初始化DHT11传感器
  117.     if(connectWifi()){
  118.     connectMqtt();
  119.   };

  120.   heartBeatMsg = createHeartBeatMsg(ipToString(WiFi.localIP()));
  121.   
  122.   
  123. }

  124. void loop() {
  125.   Serial.println(heartBeatMsg);
  126.   client.publish(topic, heartBeatMsg.c_str());
  127.   delay(1000);


  128.   // 读取湿度和温度值
  129.   float h = dht.readHumidity();          // 读取湿度
  130.   float t = dht.readTemperature();       // 读取温度

  131.   // 检查读取是否成功
  132.   if (isnan(h) || isnan(t)) {
  133.     Serial.println("读取DHT11失败!");  // 如果读取失败,在串口监视器打印失败信息
  134.     return;
  135.   }
  136.   // 串口打印温湿度信息
  137.   Serial.printf("湿度: %.1f%% 温度: %.1f°C\n", h, t);  // 格式化输出湿度和温度



  138.   // 打印dht数据
  139.   String dhtMsg = createDhtMsg(t,h);
  140.   Serial.println(dhtMsg);
  141.   client.publish(topic, dhtMsg.c_str());


  142.   delay(2000);
  143. }
复制代码




本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册 微信登录

x

打赏

参与人数 1家元 +7 收起 理由
keye + 7 謝謝分享

查看全部打赏

发表于 2025-2-21 08:12:52 | 显示全部楼层
让esp32  powerdown、时钟隔一定分钟数唤醒,甚至可以用电池供电
回复 支持 反对

使用道具 举报

发表于 2025-2-22 23:38:58 | 显示全部楼层
mqtt是真的很方便
回复 支持 反对

使用道具 举报

 楼主| 发表于 2025-7-5 19:27:36 | 显示全部楼层
devcang 发表于 2025-2-21 08:12
让esp32  powerdown、时钟隔一定分钟数唤醒,甚至可以用电池供电

学习了,后续试下。
回复 支持 反对

使用道具 举报

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

本版积分规则

APP|手机版|小黑屋|关于我们|联系我们|法律条款|技术知识分享平台

闽公网安备35020502000485号

闽ICP备2021002735号-2

GMT+8, 2025-7-31 00:50 , Processed in 0.078000 second(s), 8 queries , Redis On.

Powered by Discuz!

© 2006-2025 MyDigit.Net

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