ESP32 MQTT –使用Arduino IDE发布和订阅


功能介绍

该项目展示了如何将MQTT通信协议与ESP32一起使用来发布消息和订阅主题。 例如,我们将BME280传感器的读数发布到Node-RED仪表板,并控制ESP32输出。 我们将使用Arduino IDE对ESP32进行编程。

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


在此示例中,有一个Node-RED应用程序,该应用程序使用MQTT通信协议控制ESP32的输出并从ESP32接收传感器读数。 Node-RED应用程序在Raspberry Pi上运行。

我们将使用安装在同一Raspberry Pi上的Mosquitto代理。 代理负责接收所有消息,过滤消息,确定谁对它们感兴趣并将消息发布到所有订阅的客户端。

下图概述了本教程将要执行的操作。

在这里插入图片描述
Node-RED应用程序在主题esp32 / output中发布消息(“ on”或“ off”)。 ESP32已订阅该主题。 因此,它接收到带有“开”或“关”的消息,以打开或关闭LED。
ESP32在esp32 /温度主题上发布温度,在esp32 /湿度主题上发布湿度。 Node-RED应用程序已订阅这些主题。 因此,它接收的温度和湿度读数可以显示在图表或仪表上。

一、介绍BME280传感器模块

BME280传感器模块读取温度,湿度和压力。 由于压力随海拔高度而变化,因此您也可以估算海拔高度。 但是,在本教程中,我们将仅读取温度和湿度。 该传感器模块有多种版本,但我们使用的是下图所示的版本。
传感器可以使用SPI或I2C通信协议进行通信(该传感器的某些模块仅与I2C进行通信,这些模块仅带有四个引脚)。

要使用SPI通信协议,请使用以下引脚:
SCK – this is the SPI Clock pin

  • SDO – MISO
  • SDI – MOSI
  • CS – Chip Select

To use I2C communication protocol, the sensor uses the following pins:

  • SCK – SCL pin
  • SDI – SDA pin

二、准备Arduino IDE

Arduino IDE有一个附加组件,可让您使用Arduino IDE及其编程语言对ESP32进行编程。 如果您尚未使用Arduino IDE,请按照以下教程之一进行准备,以使其能够与ESP32一起使用。

二、安装PubSubClient库

PubSubClient库提供了一个客户端,用于使用支持MQTT的服务器(基本上允许您的ESP32与Node-RED进行通信)来进行简单的发布/订阅消息传递。

单击此处下载PubSubClient库。 您的下载文件夹中应该有一个.zip文件夹
解压缩.zip文件夹,您应该获得pubsubclient-master文件夹

将文件夹从pubsubclient-master重命名为pubsubclient
将pubsubclient文件夹移至Arduino IDE安装库文件夹
然后,重新打开您的Arduino IDE
该库附带了许多示例草图。 请参阅Arduino IDE软件中的“文件”>“示例”>“ PubSubClient”。

重要提示:PubSubClient与ESP32并不完全兼容,但本教程中提供的示例在我们的测试过程中工作非常可靠。

三、安装BME280库

要获取BME280传感器模块的读数,我们将使用Adafruit_BME280库。 请按照以下步骤在您的Arduino IDE中安装该库:

单击此处下载Adafruit-BME280库。 您的下载文件夹中应该有一个.zip文件夹
解压缩.zip文件夹,您应该会获得Adafruit-BME280-Library-master文件夹
将文件夹从Adafruit-BME280-Library-master重命名为Adafruit_BME280_Library
将Adafruit_BMPE280_Library文件夹移至Arduino IDE安装库文件夹
最后,重新打开您的Arduino IDE

四、安装Adafruit_Sensor库

要使用BME280库,您还需要安装Adafruit_Sensor库。 请按照以下步骤安装该库:

单击此处下载Adafruit_Sensor库。 您的下载文件夹中应该有一个.zip文件夹
解压缩.zip文件夹,您应该获得Adafruit_Sensor-master文件夹
将文件夹从Adafruit_Sensor-master重命名为Adafruit_Sensor
将Adafruit_Sensor文件夹移至Arduino IDE安装库文件夹
最后,重新打开您的Arduino IDE
上载程式码
现在,您可以将以下代码上传到ESP32。 该代码会在需要更改的地方添加注释。 您需要使用自己的SSID,密码和Raspberry Pi IP地址来编辑代码。

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>

// Replace the next variables with your SSID/Password combination
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "YOUR_MQTT_BROKER_IP_ADDRESS";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

//uncomment the following lines if you're using SPI
/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
float temperature = 0;
float humidity = 0;

// LED Pin
const int ledPin = 4;

void setup() {
  Serial.begin(115200);
  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  //status = bme.begin();  
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(ledPin, OUTPUT);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
  // Changes the output state according to the message
  if (String(topic) == "esp32/output") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    
    // Temperature in Celsius
    temperature = bme.readTemperature();   
    // Uncomment the next line to set temperature in Fahrenheit 
    // (and comment the previous temperature line)
    //temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit
    
    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
    Serial.print("Temperature: ");
    Serial.println(tempString);
    client.publish("esp32/temperature", tempString);

    humidity = bme.readHumidity();
    
    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print("Humidity: ");
    Serial.println(humString);
    client.publish("esp32/humidity", humString);
  }
}

该代码通过MQTT协议发布有关esp32 /温度和esp32 /湿度主题的温度和湿度读数。

ESP32订阅了esp32 / output主题,以接收Node-RED应用程序在该主题上发布的消息。 然后,根据收到的消息,它打开或关闭LED。

订阅MQTT主题
在reconnect()函数中,您可以订阅MQTT主题。 在这种情况下,ESP32仅订阅esp32 / output:

client.subscribe(“ esp32 / output”);
在callback()函数中,ESP32接收已订阅主题的MQTT消息。 根据MQTT主题和消息,它打开或关闭LED:

发布MQTT消息
在loop()中,每5秒发布一次新的读数:

  • 27
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,以下是用Arduino IDEESP32使用MQTT远程控制LED的实验分析: 1. 准备材料 - ESP32开发板 - LED灯 - 杜邦线 - 电阻(220欧姆) 2. 连接电路 将LED灯连接到ESP32开发板上,具体如下: - 将LED的一端连接到ESP32的D5引脚上 - 将LED的另一端接到一个220欧姆电阻上 - 将电阻的另一端连接到ESP32的GND引脚上 3. 安装MQTT库 在Arduino IDE中打开“工具”菜单,选择“管理库”,搜索并安装“PubSubClient”库,这是MQTT的客户端库。 4. 编写程序 以下是一个简单的程序,用于连接MQTT服务器并接收远程发送的消息,从而控制LED灯的开关: ```c++ #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); int ledPin = 5; char message_buff[100]; void setup() { pinMode(ledPin, OUTPUT); 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(); } void callback(char* topic, byte* message, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.print(". Message: "); String messageTemp; for (int i = 0; i < length; i++) { Serial.print((char)message[i]); messageTemp += (char)message[i]; } Serial.println(); if (String(topic) == "led") { if (messageTemp == "on") { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } } } void reconnect() { while (!client.connected()) { Serial.println("Connecting to MQTT..."); String clientId = "ESP32Client-"; clientId += String(random(0xffff), HEX); if (client.connect(clientId.c_str())) { Serial.println("Connected to MQTT"); client.subscribe("led"); } else { Serial.print("Failed to connect to MQTT, rc="); Serial.println(client.state()); delay(5000); } } } ``` 5. 配置MQTT服务器 在程序中需要配置MQTT服务器的参数,包括服务器地址、端口号、用户身份验证等。 6. 上传程序 将程序上传到ESP32开发板上。 7. 使用MQTT客户端发送消息 使用MQTT客户端向ESP32发送消息,例如发送“led/on”即可打开LED灯。 通过以上步骤,我们就可以通过MQTT远程控制LED的开关了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

物联网程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值