ESP32配置mqtt arduino

ESP32配置MQTT

明确流程
1. 需要在arduino上使用mqtt需要使用库 " PubSubClient "。
2. 使ESP32连接到WiFi网络
3. 连接mqtt代理
4. 订阅主题
5. 发布信息

安装库:

打开arduino选择“工具”里的管理库,在管理库里搜索:Pub SubClient,安装完成后即可使用该库。
在这里插入图片描述

在这里先贴上代码,需要可直接copy

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

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "your_MQTT_SERVER";

WiFiClient espClient;
PubSubClient client(espClient);

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

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
      client.subscribe("test/topic1");
      client.subscribe("test/topic2");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

想继续了解的往下看(部分代码与上述不一致)

ESP32连接到WiFi网络:确定连接WiFi的SSID和password,只需更改示例代码的ssid和password
示例代码

#include <WiFi.h>

const char* ssid = "SSID";
const char* password = "PASSWORD";

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}

void loop() {
}

连接mqtt

先创建一个mqtt示例

WiFiClient espClient;
PubSubClient client(espClient);

"WiFiClient"是一个用于建立 TCP 连接的类,而 PubSubClient是一个 MQTT 客户端库,用于发布和接收 MQTT 消息。
在这里,WiFiClient 用于建立与 MQTT 服务器的连接,而 PubSubClient用于发布和接收 MQTT 消息。

确定mqtt服务器

client.setServer(mqtt_server, 1883);

mqtt连接并使用回调 – 需要账号密码类型

const char* mqtt_server = "";    //改自己的
const char* mqtt_username = "";
const char* mqtt_password = "";

while (!client.connected()) {
    Serial.println("Connecting to MQTT server...");
    if (client.connect("ESP32", mqtt_username, mqtt_password)) {
      Serial.println("Connected to MQTT server");
      client.subscribe("topic1");
      client.subscribe("topic2");
    } else {
      Serial.print("Failed to connect to MQTT server, rc=");
      Serial.print(client.state());
      Serial.println(" retrying in 5 seconds");
      delay(500);
    }
  }

参照下列填写连接函数参数

boolean connect (clientID, [username, password], [willTopic, willQoS, willRetain, willMessage], [cleanSession])
Parameters
clientID const char[] - the client ID to use when connecting to the server
Credentials - (optional)
username const char[] - the username to use. If NULL, no username or password is used
password const char[] - the password to use. If NULL, no password is used
Will - (optional)
willTopic const char[] - the topic to be used by the will message
willQoS int: 0,1 or 2 - the quality of service to be used by the will message
willRetain boolean - whether the will should be published with the retain flag
willMessage const char[] - the payload of the will message
cleanSession boolean (optional) - whether to connect clean-session or not

回调函数讲解

void callback(char* topic, byte* payload, unsigned int length)

callback函数是一种函数指针,它指向一个函数。当事件发生时,系统会自动调用这个函数。在Arduino中,callback函数通常用于处理中断事件。例如,当一个按钮被按下时,系统会自动调用一个callback函数来处理这个事件。
在代码中,callback函数被定义为一个带有三个参数的函数:char* topicbyte* payloadunsigned int length。当一个消息到达时,系统会自动调用这个函数,并将消息的主题、有效载荷和长度作为参数传递给它。

如何发布信息?
首先确认需要向那个主题发布信息、信息质量和信息体
例如下列这个简单例子

void loop() {
char message[50];
sprintf(message, "Hello from ESP32");
client.publish("test_topic", message);
delay(5000);
}

使用的前提是mqtt成功连接

提问:如何订阅两个主题并且区分接收到的mqtt信息属于那个主题?

非常简单即可做到!

posted @ 2023-03-25 12:42  lhy_1016  阅读(864)  评论(0编辑  收藏  举报  来源