esp32 arduino mqtt的连接代码
时间: 2023-08-27 16:37:29 浏览: 247
ESP32连接阿里云MQTT物联网平台的Arduino支持库及示例代码。
5星 · 资源好评率100%
以下是ESP32 Arduino连接到MQTT服务器的示例代码:
```C++
#include <WiFi.h>
#include <PubSubClient.h>
// Replace the variables below with your network credentials and MQTT broker details
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqttServer = "your_MQTT_broker_server_address";
const int mqttPort = 1883;
const char* mqttUser = "your_MQTT_username";
const char* mqttPassword = "your_MQTT_password";
WiFiClient espClient;
PubSubClient client(espClient);
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(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT");
client.subscribe("testTopic");
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message received on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
messageTemp += (char)message[i];
}
Serial.println(messageTemp);
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT");
client.subscribe("testTopic");
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
```
这个代码使用了ESP32的WiFi库和PubSubClient库。在代码中,你需要替换以下变量:
- `ssid`:你的无线网络名称。
- `password`:你的无线网络密码。
- `mqttServer`:你的MQTT服务器地址。
- `mqttPort`:MQTT服务器端口号,默认为1883。
- `mqttUser`:你的MQTT服务器用户名。
- `mqttPassword`:你的MQTT服务器密码。
在`setup()`函数中,我们连接到WiFi和MQTT服务器,并订阅了`testTopic`主题。在`loop()`函数中,我们检查是否连接到MQTT服务器,如果没有连接,则调用`reconnect()`函数进行重新连接。在`callback()`函数中,我们打印接收到的消息。
注意:在使用此代码之前,请确保你已经在你的网络中安装了MQTT服务器。
阅读全文