如何在ESP8266的MQTT中合并发布服务器订阅服务器代码?

如何在ESP8266的MQTT中合并发布服务器订阅服务器代码?,mqtt,esp8266,Mqtt,Esp8266,我是ESP8266和MQTT的新手。最近,我尝试在MQTT中合并发布者和订阅者的两个独立代码,以便我的ESP8266可以同时发布和订阅不同的主题。据我所知,它们在合并时从不工作,而是单独工作。 请指导我如何合并它们,或者如果有可用的合并代码,请共享 发行商代码: #include <Bounce2.h> // Used for "debouncing" the pushbutton #include <ESP8266WiFi.h> // Enables the ESP82

我是ESP8266和MQTT的新手。最近,我尝试在MQTT中合并发布者和订阅者的两个独立代码,以便我的ESP8266可以同时发布和订阅不同的主题。据我所知,它们在合并时从不工作,而是单独工作。 请指导我如何合并它们,或者如果有可用的合并代码,请共享

发行商代码:

#include <Bounce2.h> // Used for "debouncing" the pushbutton
#include <ESP8266WiFi.h> // Enables the ESP8266 to connect to the local network (via WiFi)
#include <PubSubClient.h> // Allows us to connect to, and publish to the MQTT broker

const int ledPin = 0; // This code uses the built-in led for visual feedback that the button has been pressed
const int buttonPin = 13; // Connect your button to pin #13

// WiFi
// Make sure to update this for your own WiFi network!
const char* ssid = "TP-LINK_7224";
const char* wifi_password = "RFID7890";

// MQTT
// Make sure to update this for your own MQTT Broker!
const char* mqtt_server = "192.168.71.107";
const char* mqtt_topic = "Flash_Message";
const char* mqtt_username = "pi";
const char* mqtt_password = "pi123";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "ESP01";

// Initialise the Pushbutton Bouncer object
Bounce bouncer = Bounce();

// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  // Switch the on-board LED off to start with
  digitalWrite(ledPin, HIGH);

  // Setup pushbutton Bouncer object
  bouncer.attach(buttonPin);
  bouncer.interval(5);

  // Begin Serial on 115200
  // Remember to choose the correct Baudrate on the Serial monitor!
  // This is just for debugging purposes
  Serial.begin(115200);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Connect to the WiFi
  WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Debugging - Output the IP Address of the ESP8266
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Connect to MQTT Broker
  // client.connect returns a boolean value to let us know if the connection was successful.
  // If the connection is failing, make sure you are using the correct MQTT Username and Password (Setup Earlier in the Instructable)
  if (client.connect(clientID, mqtt_username, mqtt_password)) {
    Serial.println("Connected to MQTT Broker!");
  }
  else {
    Serial.println("Connection to MQTT Broker failed...");
  }

}

void loop() {
  // Update button state
  // This needs to be called so that the Bouncer object can check if the button has been pressed
  bouncer.update();

  if (bouncer.rose()) {
    // Turn light on when button is pressed down
    // (i.e. if the state of the button rose from 0 to 1 (not pressed to pressed))
    digitalWrite(ledPin, LOW);

    // PUBLISH to the MQTT Broker (topic = mqtt_topic, defined at the beginning)
    // Here, "Button pressed!" is the Payload, but this could be changed to a sensor reading, for example.
    if (client.publish(mqtt_topic, "Button pressed!")) {
      Serial.println("Button pushed and message sent!");
    }
    // Again, client.publish will return a boolean value depending on whether it succeded or not.
    // If the message failed to send, we will try again, as the connection may have broken.
    else {
      Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
      client.connect(clientID, mqtt_username, mqtt_password);
      delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call
      client.publish(mqtt_topic, "Button pressed!");
    }
  }
  else if (bouncer.fell()) {
    // Turn light off when button is released
    // i.e. if state goes from high (1) to low (0) (pressed to not pressed)
    digitalWrite(ledPin, HIGH);
  }
}
#include <ESP8266WiFi.h> // Enables the ESP8266 to connect to the local network (via WiFi)
#include <PubSubClient.h> // Allows us to connect to, and publish to the MQTT broker

const int ledPin = 16; // This code uses the built-in led for visual feedback that a message has been received

// WiFi
// Make sure to update this for your own WiFi network!
const char* ssid = "TP-LINK_7224";
const char* wifi_password = "RFID7890";

// MQTT
// Make sure to update this for your own MQTT Broker!
const char* mqtt_server = "192.168.71.127";
const char* mqtt_topic = "flash";
const char* mqtt_username = "pi";
const char* mqtt_password = "pi123";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "ESP01";

// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker

void ReceivedMessage(char* topic, byte* payload, unsigned int length) {
  // Output the first character of the message to serial (debug)
  Serial.println((char)payload[0]);

  // Handle the message we received
  // Here, we are only looking at the first character of the received message (payload[0])
  // If it is 0, turn the led off.
  // If it is 1, turn the led on.
  if ((char)payload[0] == 'E' && (char)payload[1] == 'S' && (char)payload[2] == 'P' && (char)payload[3] == '0' && (char)payload[4] == '1' ) {

    digitalWrite(ledPin, HIGH); 
    delay(4000);// Notice for the HUZZAH Pin 0, HIGH is OFF and LOW is ON. Normally it is the other way around.
    digitalWrite(ledPin, LOW);
  }
  if ((char)payload[0] == '0') {
    digitalWrite(ledPin, LOW);
    delay(1000);
  }
}

bool Connect() {
  // Connect to MQTT Server and subscribe to the topic
  if (client.connect(clientID, mqtt_username, mqtt_password)) {
      client.subscribe(mqtt_topic);
      return true;
    }
    else {
      return false;
  }
}

void setup() {
  pinMode(ledPin, OUTPUT);

  // Switch the on-board LED off to start with
//  digitalWrite(ledPin, HIGH);
  digitalWrite(ledPin, LOW);

  // Begin Serial on 115200
  // Remember to choose the correct Baudrate on the Serial monitor!
  // This is just for debugging purposes
  Serial.begin(115200);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Connect to the WiFi
  WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Debugging - Output the IP Address of the ESP8266
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Connect to MQTT Broker
  // setCallback sets the function to be called when a message is received.
  client.setCallback(ReceivedMessage);
  if (Connect()) {
    Serial.println("Connected Successfully to MQTT Broker!");  
  }
  else {
    Serial.println("Connection Failed!");
  }
}

void loop() {
  // If the connection is lost, try to connect again
  if (!client.connected()) {
    Connect();
  }
  // client.loop() just tells the MQTT client code to do what it needs to do itself (i.e. check for messages, etc.)
  client.loop();
  // Once it has done all it needs to do for this cycle, go back to checking if we are still connected.
}
#include//用于“去抖动”按钮
#include//使ESP8266能够连接到本地网络(通过WiFi)
#include//允许我们连接并发布到MQTT代理
常量int ledPin=0;//此代码使用内置led提供按钮已按下的视觉反馈
常量int buttonPin=13;//将按钮连接到针脚13
//无线网络
//请确保为您自己的WiFi网络更新此信息!
const char*ssid=“TP-LINK_7224”;
const char*wifi_password=“RFID7890”;
//MQTT
//请确保为您自己的MQTT代理更新此文件!
const char*mqtt_server=“192.168.71.107”;
const char*mqtt_topic=“Flash_Message”;
常量字符*mqtt_username=“pi”;
const char*mqtt_password=“pi123”;
//客户端id标识ESP8266设备。把它想象成一个主机名(或者只是一个名字,比如Greg)。
const char*clientID=“ESP01”;
//初始化按钮弹跳器对象
弹跳器=弹跳();
//初始化WiFi和MQTT客户端对象
WiFiClient WiFiClient;
PubSubClient客户端(mqtt_服务器,1883,wifiClient);//1883是代理的侦听器端口
无效设置(){
引脚模式(LED引脚,输出);
pinMode(按钮输入,输入);
//关闭车载LED以启动
数字写入(ledPin,高电平);
//设置按钮弹跳器对象
弹跳器。连接(按钮插入);
弹跳间隔(5);
//从115200开始
//记住在串行监视器上选择正确的波特率!
//这只是为了调试目的
序列号开始(115200);
串行打印(“连接到”);
序列号println(ssid);
//连接到WiFi
WiFi.begin(ssid、WiFi_密码);
//等待确认连接后再继续
while(WiFi.status()!=WL_已连接){
延迟(500);
连续打印(“.”);
}
//调试-输出ESP8266的IP地址
Serial.println(“WiFi连接”);
串行打印(“IP地址:”);
Serial.println(WiFi.localIP());
//连接到MQTT代理
//client.connect返回一个布尔值,让我们知道连接是否成功。
//如果连接失败,请确保您使用的是正确的MQTT用户名和密码(在可指示的
if(client.connect(clientID、mqtt_用户名、mqtt_密码)){
Serial.println(“连接到MQTT代理!”);
}
否则{
Serial.println(“连接到MQTT代理失败…”);
}
}
void循环(){
//更新按钮状态
//需要调用此选项,以便Bouncer对象可以检查按钮是否已按下
buuncer.update();
if(bouncer.rose()){
//按下按钮时打开灯
//(即,如果按钮的状态从0上升到1(未按下到按下))
数字写入(ledPin,低电平);
//发布到MQTT代理(topic=MQTT_topic,在开头定义)
//这里,“按钮按下!”是有效载荷,但这可以更改为传感器读数,例如。
if(client.publish(mqtt_主题,“按钮按下!”){
Serial.println(“按下按钮并发送消息!”);
}
//同样,client.publish将根据是否成功返回布尔值。
//如果消息发送失败,我们将重试,因为连接可能已断开。
否则{
Serial.println(“消息发送失败。重新连接到MQTT代理并重试”);
connect(clientID、mqtt_用户名、mqtt_密码);
延迟(10);//此延迟确保client.publish不会与client.connect调用冲突
发布(mqtt_主题,“按钮按下!”);
}
}
else if(bouncer.fall()){
//松开按钮时关闭灯
//即,如果状态从高(1)变为低(0)(按下到未按下)
数字写入(ledPin,高电平);
}
}
用户代码:

#include <Bounce2.h> // Used for "debouncing" the pushbutton
#include <ESP8266WiFi.h> // Enables the ESP8266 to connect to the local network (via WiFi)
#include <PubSubClient.h> // Allows us to connect to, and publish to the MQTT broker

const int ledPin = 0; // This code uses the built-in led for visual feedback that the button has been pressed
const int buttonPin = 13; // Connect your button to pin #13

// WiFi
// Make sure to update this for your own WiFi network!
const char* ssid = "TP-LINK_7224";
const char* wifi_password = "RFID7890";

// MQTT
// Make sure to update this for your own MQTT Broker!
const char* mqtt_server = "192.168.71.107";
const char* mqtt_topic = "Flash_Message";
const char* mqtt_username = "pi";
const char* mqtt_password = "pi123";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "ESP01";

// Initialise the Pushbutton Bouncer object
Bounce bouncer = Bounce();

// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  // Switch the on-board LED off to start with
  digitalWrite(ledPin, HIGH);

  // Setup pushbutton Bouncer object
  bouncer.attach(buttonPin);
  bouncer.interval(5);

  // Begin Serial on 115200
  // Remember to choose the correct Baudrate on the Serial monitor!
  // This is just for debugging purposes
  Serial.begin(115200);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Connect to the WiFi
  WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Debugging - Output the IP Address of the ESP8266
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Connect to MQTT Broker
  // client.connect returns a boolean value to let us know if the connection was successful.
  // If the connection is failing, make sure you are using the correct MQTT Username and Password (Setup Earlier in the Instructable)
  if (client.connect(clientID, mqtt_username, mqtt_password)) {
    Serial.println("Connected to MQTT Broker!");
  }
  else {
    Serial.println("Connection to MQTT Broker failed...");
  }

}

void loop() {
  // Update button state
  // This needs to be called so that the Bouncer object can check if the button has been pressed
  bouncer.update();

  if (bouncer.rose()) {
    // Turn light on when button is pressed down
    // (i.e. if the state of the button rose from 0 to 1 (not pressed to pressed))
    digitalWrite(ledPin, LOW);

    // PUBLISH to the MQTT Broker (topic = mqtt_topic, defined at the beginning)
    // Here, "Button pressed!" is the Payload, but this could be changed to a sensor reading, for example.
    if (client.publish(mqtt_topic, "Button pressed!")) {
      Serial.println("Button pushed and message sent!");
    }
    // Again, client.publish will return a boolean value depending on whether it succeded or not.
    // If the message failed to send, we will try again, as the connection may have broken.
    else {
      Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
      client.connect(clientID, mqtt_username, mqtt_password);
      delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call
      client.publish(mqtt_topic, "Button pressed!");
    }
  }
  else if (bouncer.fell()) {
    // Turn light off when button is released
    // i.e. if state goes from high (1) to low (0) (pressed to not pressed)
    digitalWrite(ledPin, HIGH);
  }
}
#include <ESP8266WiFi.h> // Enables the ESP8266 to connect to the local network (via WiFi)
#include <PubSubClient.h> // Allows us to connect to, and publish to the MQTT broker

const int ledPin = 16; // This code uses the built-in led for visual feedback that a message has been received

// WiFi
// Make sure to update this for your own WiFi network!
const char* ssid = "TP-LINK_7224";
const char* wifi_password = "RFID7890";

// MQTT
// Make sure to update this for your own MQTT Broker!
const char* mqtt_server = "192.168.71.127";
const char* mqtt_topic = "flash";
const char* mqtt_username = "pi";
const char* mqtt_password = "pi123";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "ESP01";

// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker

void ReceivedMessage(char* topic, byte* payload, unsigned int length) {
  // Output the first character of the message to serial (debug)
  Serial.println((char)payload[0]);

  // Handle the message we received
  // Here, we are only looking at the first character of the received message (payload[0])
  // If it is 0, turn the led off.
  // If it is 1, turn the led on.
  if ((char)payload[0] == 'E' && (char)payload[1] == 'S' && (char)payload[2] == 'P' && (char)payload[3] == '0' && (char)payload[4] == '1' ) {

    digitalWrite(ledPin, HIGH); 
    delay(4000);// Notice for the HUZZAH Pin 0, HIGH is OFF and LOW is ON. Normally it is the other way around.
    digitalWrite(ledPin, LOW);
  }
  if ((char)payload[0] == '0') {
    digitalWrite(ledPin, LOW);
    delay(1000);
  }
}

bool Connect() {
  // Connect to MQTT Server and subscribe to the topic
  if (client.connect(clientID, mqtt_username, mqtt_password)) {
      client.subscribe(mqtt_topic);
      return true;
    }
    else {
      return false;
  }
}

void setup() {
  pinMode(ledPin, OUTPUT);

  // Switch the on-board LED off to start with
//  digitalWrite(ledPin, HIGH);
  digitalWrite(ledPin, LOW);

  // Begin Serial on 115200
  // Remember to choose the correct Baudrate on the Serial monitor!
  // This is just for debugging purposes
  Serial.begin(115200);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Connect to the WiFi
  WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Debugging - Output the IP Address of the ESP8266
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Connect to MQTT Broker
  // setCallback sets the function to be called when a message is received.
  client.setCallback(ReceivedMessage);
  if (Connect()) {
    Serial.println("Connected Successfully to MQTT Broker!");  
  }
  else {
    Serial.println("Connection Failed!");
  }
}

void loop() {
  // If the connection is lost, try to connect again
  if (!client.connected()) {
    Connect();
  }
  // client.loop() just tells the MQTT client code to do what it needs to do itself (i.e. check for messages, etc.)
  client.loop();
  // Once it has done all it needs to do for this cycle, go back to checking if we are still connected.
}
\include//使ESP8266能够连接到本地网络(通过WiFi)
#include//允许我们连接并发布到MQTT代理
常数int ledPin=16;//此代码使用内置led进行视觉反馈,表示已收到消息
//无线网络
//请确保为您自己的WiFi网络更新此信息!
const char*ssid=“TP-LINK_7224”;
const char*wifi_password=“RFID7890”;
//MQTT
//请确保为您自己的MQTT代理更新此文件!
const char*mqtt_server=“192.168.71.127”;
const char*mqtt_topic=“flash”;
常量字符*mqtt_username=“pi”;
const char*mqtt_password=“pi123”;
//客户端id标识ESP8266设备。把它想象成一个主机名(或者只是一个名字,比如Greg)。
const char*clientID=“ESP01”;
//初始化WiFi和MQTT客户端对象
WiFiClient WiFiClient;
PubSubClient客户端(mqtt_服务器,1883,wifiClient);//1883是代理的侦听器端口
void ReceivedMessage(字符*主题,字节*有效负载,无符号整数长度){
//将消息的第一个字符输出到串行(调试)
Serial.println((char)有效载荷[0]);
//处理我们收到的信息
//这里,我们只看接收到的消息的第一个字符(有效负载[0])
//如果为0,则关闭led。
//如果为1,则打开led。
如果((字符)有效载荷[0]='E'&&&(字符)有效载荷[1]='S'&&(字符)有效载荷[2]='P'&&(字符)有效载荷[3]='0'&&(字符)有效载荷[4]='1'){
数字写入(ledPin,高电平);
延迟(4000);//注意,对于HUZZAH引脚0,高电平是关闭的,低电平是打开的。通常情况下,情况正好相反。
数字写入(ledPin,低电平);
}
如果((字符)有效负载[0]=“0”){
数字写入(ledPin,低电平);
延迟(1000);
}
}
boolconnect(){
//连接到MQTT