esp32 arduino mqtt的连接代码中mqttserver该怎么写,例子
时间: 2024-03-26 22:39:36 浏览: 87
Arduino开发ESP32通过PubSubClient连上阿里云MQTT
4星 · 用户满意度95%
如果你想在ESP32 Arduino中连接到MQTT服务器,以下是一个示例代码,你可以将其中的`mqttServer`变量替换为你的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"; // 替换为你的MQTT服务器地址
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);
}
}
}
```
在这个代码中,我们使用`mqttServer`变量来保存MQTT服务器地址,你只需要将它替换为你自己的MQTT服务器地址即可。
阅读全文