ESP32 MQTT发布订阅:PubSubClient实操

2026-11-16 13:11:53 62阅读 所属项目:ESP32 开发板
ESP32 MQTT PubSubClient 发布订阅

玩ROS的都熟悉这个场景:节点之间用话题通信,rostopic pub一发,subscriber那头就收到了。ESP32想加入这套体系,第一步就是MQTT。这个教程的底子来自Random Nerd Tutorials那篇ESP32 MQTT publish/subscribe,我把它拆开讲清楚,重点放在PubSubClient怎么装、broker怎么连、发布和订阅代码每一块在干什么。

MQTT一句话讲完:所有设备连到一台叫broker的服务器上,一台设备往某个topic(比如esp32/temperature)发布消息,其他设备订阅了这个topic就能收到——发布者和订阅者互相不知道对方存在,全靠broker中转。跟ROS的话题机制几乎一个思路,只是broker不在本机,而在网络上。

底稿的演示方案是ESP32加BME280温湿度传感器,每5秒把温度和湿度发到broker,同时订阅esp32/output这个topic来控制GPIO4上的LED。broker用的是你自己的地址,代码里也支持broker.emqx.io这类公共broker,不用自己搭服务就能跑通。

准备工作:库和硬件

需要的库一共四个,都在Arduino IDE的库管理器里能装到:Adafruit BME280 Library、Adafruit Unified Sensor、PubSubClient(作者是Nick O'Leary),WiFi.h是ESP32板载支持自带的。装PubSubClient的时候注意选Library Manager里官方那个,别装到同名的老分支。硬件方面ESP32开发板一块,BME280传感器接到I2C默认引脚(GPIO21是SDA、GPIO22是SCL),传感器地址按底稿用0x76,另外GPIO4接一个LED做订阅控制的输出。

ESP32与BME280的I2C接线面包板图

接线就这几根:BME280的VCC接3.3V,GND共地,SDA/SCL分别到GPIO21/22,LED阳极串电阻接GPIO4。注意BME280模块有0x76和0x77两种默认地址,买错了begin()会找不到传感器,串口会报Could not find a valid BME280 sensor。

完整代码

下面是底稿的完整程序,逐字照搬。把ssid、password换成你家WiFi,mqtt_server换成你的broker地址——如果没有自己的broker,broker.emqx.io这个公共的可以直接填,端口1883。头文件用了引号写法,在Arduino IDE下与尖括号写法对库搜索路径等价。

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

#include "WiFi.h"
#include "PubSubClient.h"
#include "Wire.h"
#include "Adafruit_BME280.h"
#include "Adafruit_Sensor.h"

// Replace the next variables with your SSID/Password combination
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "YOUR_MQTT_BROKER_IP_ADDRESS";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

//uncomment the following lines if you're using SPI
/*#include "SPI.h"
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
float temperature = 0;
float humidity = 0;

// LED Pin
const int ledPin = 4;

void setup() {
  Serial.begin(115200);
  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  //status = bme.begin();  
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(ledPin, OUTPUT);
}

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());
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
  // Changes the output state according to the message
  if (String(topic) == "esp32/output") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    
    // Temperature in Celsius
    temperature = bme.readTemperature();   
    // Uncomment the next line to set temperature in Fahrenheit 
    // (and comment the previous temperature line)
    //temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit
    
    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
    Serial.print("Temperature: ");
    Serial.println(tempString);
    client.publish("esp32/temperature", tempString);

    humidity = bme.readHumidity();
    
    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print("Humidity: ");
    Serial.println(humString);
    client.publish("esp32/humidity", humString);
  }
}

三个关键点:setServer、setCallback、reconnect

连broker的骨架就三行:先建WiFiClient再把它交给PubSubClient构造;setup()里client.setServer(mqtt_server, 1883)指定broker地址和端口,MQTT默认端口1883,TLS才是8883;client.setCallback(callback)注册收到消息时的处理函数。这个骨架和ROS里NodeHandle+advertise+subscribe的搭配很像,都是"注册回调、消息驱动"。

发布那半边的逻辑在loop()里:用millis()做定时,每5000毫秒读一次BME280,浮点数经dtostrf转成char数组才能发布,因为PubSubClient的publish收的是字符缓冲,不是String。topic命名用斜杠分层,esp32/temperature、esp32/humidity,这也是MQTT的惯例。

订阅那半边在callback里,收到消息后按topic分发。底稿的逻辑是只有esp32/output这个topic才处理,消息是on就拉高GPIO4、off就拉低:

// If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
// Changes the output state according to the message
if (String(topic) == "esp32/output") {
  Serial.print("Changing output to ");
  if (messageTemp == "on") {
    Serial.println("on");
    digitalWrite(ledPin, HIGH);
  }
  else if (messageTemp == "off") {
    Serial.println("off");
    digitalWrite(ledPin, LOW);
  }
}

注意callback的第三个参数length:消息内容是byte*加长度,不是C字符串,遍历时必须按length来,不能假设末尾有'\0'。这是新手把消息拼串时最常见的出错点。

QoS和keepalive是怎么回事

MQTT有三种服务质量等级:QoS 0发完即忘、QoS 1至少送达一次(可能重复)、QoS 2恰好一次(握手最多)。PubSubClient支持QoS 0和1,publish()和subscribe()都可以带QoS参数,不填默认0。对温湿度这种周期性数据,QoS 0完全够用;控制指令类的消息建议上QoS 1,保证LED那种开关指令不丢。

keepalive是客户端和broker约定的心跳间隔,PubSubClient的connect()默认15秒,期间client.loop()会自动处理心跳和收包。所以loop()里那句client.loop()千万别省,很多人"为什么收不到消息"就是因为它被delay卡死了——只要loop()里有长delay,心跳和回调都停摆。

常见坑:buffer大小和重连

第一个坑是PubSubClient默认消息缓冲区只有256字节。发布的payload超长会被静默截断,收不到完整数据。解决办法是connect之前调client.setBufferSize(1024)(库2.6以上支持),或者精简payload。发JSON串的时候尤其要注意。

第二个坑是掉线重连。WiFi和MQTT连接都会断,底稿把重连逻辑独立成reconnect()函数:没连上就一直尝试,失败打印client.state()返回码,隔5秒再来。connect的第一个参数是客户端ID,如果多台设备用同一个ID连同一个broker,会互相把对方踢下线——底稿写死ESP8266Client,多设备时记得改成唯一值,比如加个MAC后缀。

第三个坑是公共broker别发敏感数据。broker.emqx.io这类公共broker人人可连,你订阅的topic别人也能订阅,发布的消息谁都能看。做实验用没问题,真要联网的项目还是自己搭一个Mosquitto,或者用带鉴权的托管服务。

烧录之后打开串口监视器,波特率115200,能依次看到WiFi connected、MQTT connected,然后每5秒刷出温度和湿度。往esp32/output发一条on,LED亮;发off,LED灭。到这一步,ESP32就算正式接入了消息网络。

串口监视器输出的MQTT连接与温湿度数据

ESP32 MQTT发布订阅方案的通信结构图

对玩机器人的来说,这套东西的价值在于把ROS和真机连起来:ESP32这边发布传感器topic,树莓派上跑个mqtt-to-ros的桥接节点,或者在ROS2里用micro-ROS对接,机器人的网络层就有了。底稿后续还用Node-RED做了个Dashboard订阅这些topic实时显示,感兴趣可以顺着原文往下走。代码一行没改,放心抄。


作者:写launch的皮皮
链接:https://www.aiddithome.com/p/98405a2debc1f.html
本作版权归作者所有,未经允许请勿转载。若存在违规行为,您可以点击 “举报”。


登录 后发表评论
4条评论
电烙铁爱好者
1楼 · 2026-11-16 13:12:30

从ROS转过来的人看MQTT确实没门槛,pub/sub加topic就是一套平移。我踩过client.loop()被delay卡死导致心跳超时的坑,broker直接把连接踢了,查了半天才发现问题。另外多设备连同一个broker时客户端ID要唯一,写重了会互踢掉线,log里rc=-2,把ID加上MAC后缀就稳定了。

第三次终于亮了
2楼 · 2026-11-16 13:12:24

dtostrf那一步卡过我,float直接传publish报错,才知道要先转char数组

刷着刷着入坑了
3楼 · 2026-11-16 13:12:24

buffer默认256字节这个很多人不知道,发JSON基本必超,setBufferSize记得connect之前调

隔壁工位的好奇宝
4楼 · 2026-11-16 13:12:24

公共broker当沙盒用挺好,正式项目还是自己搭Mosquitto,反正一个docker的事