请帮助我,我应该尽快完成这个项目 我想使用 ESP8266、MQTT 和 Node-RED 仪表板进行项目监控 但我有一个问题,我的串行监视器显示无法连接到 MQTT “无法连接到 MQTT 代理,rc=-2” 我尝试使用 Sub 和 Pub 在 CMD 中测试我的 mqtt,我发送了一些文本,效果很好。但在我的项目中它失败了。 这是我的代码:
#include <Wire.h>
#include <Adafruit_MLX90614.h>
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Replace with your Wi-Fi credentials
const char* ssid = "mywifi";
const char* password = "password";
// Replace with your MQTT broker IP address
const char* mqttServer = "127.0.0.1";
const int mqttPort = 1883;
// Replace with your MQTT topics
const char* mqttTopicTemp = "sensors/temperature";
const char* mqttTopicOxygen = "sensors/oxygen";
WiFiClient espClient;
PubSubClient client(espClient);
Adafruit_MLX90614 mlx = Adafruit_MLX90614();
PulseOximeter pox;
void onHeartRateBeatDetected()
{
float hr = pox.getHeartRate();
Serial.print("Heart rate:");
Serial.println(hr);
}
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to MQTT broker
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
if (client.connect("ESP8266Client")) {
Serial.println("Connected to MQTT broker");
}
else {
Serial.print("Failed to connect to MQTT broker, rc=");
Serial.println(client.state());
delay(2000);
}
}
// Initialize sensors
mlx.begin();
pox.begin();
// Set up a callback for pulse detection
pox.setOnBeatDetectedCallback(onHeartRateBeatDetected);
}
void loop() {
// Read temperature from MLX90614 sensor
float temperature = mlx.readObjectTempC();
// Convert temperature to string
String tempPayload = String(temperature);
// Publish temperature to MQTT topic
client.publish(mqttTopicTemp, tempPayload.c_str());
// Update pulse oximeter
pox.update();
// Read oxygen level from MAX30100 sensor
if (pox.begin()) {
float oxygen = pox.getSpO2();
// Convert oxygen level to string
String oxygenPayload = String(oxygen);
// Publish oxygen level to MQTT topic
client.publish(mqttTopicOxygen, oxygenPayload.c_str());
}
delay(1000); // Adjust the delay based on your needs
}
我尝试使用 Sub 和 Pub 在 CMD 中测试我的 mqtt,我发送了一些文本,效果很好。但在我的项目中它失败了。
const char* mqttServer = "127.0.0.1";
127.0.0.1
始终指向代码正在运行的设备,在这种情况下,这意味着在 esp8266 上运行的代码正在尝试连接到在 esp8622 上运行的 boker。
您需要将其更改为运行 MQTT 代理的计算机的 IP 地址。
(假设您使用 Mosquitto 作为代理,您可能还需要将 Mosquitto 配置为接受来自
localhost
之外的连接,请参阅:Mosquitto:仅以本地模式启动)