基于Arduino IDE 野火ESP8266模块 MQTT 的开发

一、库介绍

 Arduino常用的MQTT库主要有PubSubClient
 PubSubClient库是一个广泛使用的MQTT客户端库,它基于MQTT 3.1.1版本,并且支持ESP8266和ESP32等Arduino兼容的硬件平台。PubSubClient库允许Arduino设备连接到MQTT服务器,发布和订阅MQTT主题,实现与其他设备或服务的通信。
 在使用PubSubClient库时,需要将其包含在Arduino项目中,并配置MQTT服务器的地址、端口、客户端ID等参数。然后可以使用库提供的函数来建立MQTT连接、发布消息到特定的主题,以及订阅并处理接收到的消息。
 除了PubSubClient库之外,还有其他一些MQTT库可供选择,但PubSubClient因其易用性和稳定性而广受欢迎。需要根据具体需求和项目环境选择适合的MQTT库。
安装完库,可查看官方的示例代码,查看方法如下:
在这里插入图片描述

官方示例代码如下:

/*Basic ESP8266 MQTT exampleThis sketch demonstrates the capabilities of the pubsub library in combinationwith the ESP8266 board/library.It connects to an MQTT server then:- publishes "hello world" to the topic "outTopic" every two seconds- subscribes to the topic "inTopic", printing out any messagesit receives. NB - it assumes the received payloads are strings not binary- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,else switch it offIt will reconnect to the server if the connection is lost using a blockingreconnect function. See the 'mqtt_reconnect_nonblocking' example for how toachieve the same result without blocking the main loop.To install the ESP8266 board, (using Arduino 1.6.4+):- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":http://arduino.esp8266.com/stable/package_esp8266com_index.json- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"- Select your ESP8266 in "Tools -> Board"
*/#include <ESP8266WiFi.h>
#include <PubSubClient.h>// Update these with values suitable for your network.const char* ssid = "........";
const char* password = "........";
const char* mqtt_server = "broker.mqtt-dashboard.com";WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;void setup_wifi() {delay(10);// We start by connecting to a WiFi networkSerial.println();Serial.print("Connecting to ");Serial.println(ssid);WiFi.mode(WIFI_STA);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}randomSeed(micros());Serial.println("");Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP());
}void callback(char* topic, byte* payload, unsigned int length) {Serial.print("Message arrived [");Serial.print(topic);Serial.print("] ");for (int i = 0; i < length; i++) {Serial.print((char)payload[i]);}Serial.println();// Switch on the LED if an 1 was received as first characterif ((char)payload[0] == '1') {digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level// but actually the LED is on; this is because// it is active low on the ESP-01)} else {digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH}}void reconnect() {// Loop until we're reconnectedwhile (!client.connected()) {Serial.print("Attempting MQTT connection...");// Create a random client IDString clientId = "ESP8266Client-";clientId += String(random(0xffff), HEX);// Attempt to connectif (client.connect(clientId.c_str())) {Serial.println("connected");// Once connected, publish an announcement...client.publish("outTopic", "hello world");// ... and resubscribeclient.subscribe("inTopic");} else {Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");// Wait 5 seconds before retryingdelay(5000);}}
}void setup() {pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an outputSerial.begin(115200);setup_wifi();client.setServer(mqtt_server, 1883);client.setCallback(callback);
}void loop() {if (!client.connected()) {reconnect();}client.loop();unsigned long now = millis();if (now - lastMsg > 2000) {lastMsg = now;++value;snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);Serial.print("Publish message: ");Serial.println(msg);client.publish("outTopic", msg);}
}

二、代码设计

代码设计思路:
1.包含库:在Arduino项目中,包含必要的库文件,特别是MQTT库(如pubsubclient)。
2.WiFi设置:设置ESP8266连接到指定的WiFi网络所需的SSID和密码。
3.MQTT服务器设置:配置MQTT服务器的地址、端口以及任何必要的认证信息(如用户名和密码)。
4.回调函数:设置MQTT连接、发布和订阅的回调函数,以便处理与MQTT服务器的通信。
5.初始化和连接:在setup()函数中初始化MQTT客户端,并尝试连接到MQTT服务器。
6.消息处理:在loop()函数中处理MQTT消息,例如发布消息到特定的主题或响应订阅的主题消息。

测试代码如下:

#include <ESP8266WiFi.h>  
#include <PubSubClient.h>  // WiFi设置  
const char* ssid = "yourSSID";  
const char* password = "yourPASSWORD";  // MQTT服务器设置  
const char* mqtt_server = "yourMQTTServer";  
const int mqtt_port = 1883;  
const char* mqtt_client_id = "ESP8266Client";  
const char* mqtt_topic = "your/topic";  //
unsigned long lastMsg = 0;WiFiClient espClient;  
PubSubClient client(espClient);  void setup_wifi() {  delay(10);  // 连接到WiFi网络  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.print("IP address: ");  Serial.println(WiFi.localIP());  
}  void reconnect() {  // Loop until we're reconnected  while (!client.connected()) {  Serial.print("Attempting MQTT connection...");  // 连接到MQTT服务器  if (client.connect(mqtt_client_id)) {  Serial.println("connected");  // 一旦连接,订阅主题  client.subscribe(mqtt_topic);  } else {  delay(5000);  }  }  
}  void callback(char* topic, byte* payload, unsigned int length) {  // 处理接收到的消息  Serial.print("Message arrived [");  Serial.print(topic);  Serial.print("] ");  for (int i = 0; i < length; i++) {  Serial.print((char)payload[i]);  }  Serial.println();  
}  void setup() {  Serial.begin(115200);  setup_wifi();  client.setServer(mqtt_server, mqtt_port);  client.setCallback(callback);  
}  void loop() {  if (!client.connected()) {  reconnect();  }  client.loop();  // 每隔一段时间发布一条消息到MQTT主题  long now = millis();  if (now - lastMsg > 2000) {  lastMsg = now;  char msg[50];  snprintf(msg, 50, "hello world at %ld", now);  client.publish(mqtt_topic, msg);  }  
}  

 请确保上述代码中的yourSSID、yourPASSWORD、yourMQTTServer、your/topic替换为实际的SSID、密码、MQTT服务器地址和主题。
 这个示例代码首先设置了WiFi连接,然后连接到MQTT服务器。一旦连接成功,它将订阅一个MQTT主题。在loop()函数中,它周期性地发布消息到该主题,并处理从该主题接收到的任何消息。
 此外,MQTT服务器的地址、端口和凭据(如果需要的话)应根据实际的MQTT服务器配置进行调整。如MQTT服务器需要用户名和密码,PubSubClient库也提供了设置这些的方法。
 上传成功后,打开串口监视器来查看ESP8266与MQTT服务器的通信日志。

三、测试结果

MQTT的参数配置如下:

// MQTT服务器设置  
const char* mqtt_server = "broker.mqtt-dashboard.com";  
const int mqtt_port = 1883;  
const char* mqtt_client_id = "ESP8266Client0326";  
const char* mqtt_topic = "test/topic";  

esp8266模块运行串口打印如下:
在这里插入图片描述更换其它服务器进行测试,如下:
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/779649.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【每日算法】dfs解决迷宫问题

迷宫问题是比较基础的dfs类型算法题。主要是针对起点和终点来求解最小行走路径 这样的题目肯定是要有回溯过程&#xff0c;因为每一个节点&#xff0c;不是只走一个方向&#xff0c;是四个方向都要走到&#xff0c;才能够知道最终能否走到终点。这样的题目dfs基本框架就是&…

微信公众号新人欢迎语消息推送

问题记录 1.使用的vue2 对象新增属性不具备响应性 this.$set(item, miniTitle, item.title) this.$set(item, miniPagepath, item.pagepath) 2.使用wangeidtor4.6.0富文本组件&#xff0c;富文本组件更改后&#xff0c;值不会马上双绑到自己的值上面 使用onchange进行绑定 …

芒果YOLOv5改进87:轻量化检测头篇:LiteShiftHead 独家原创检测头 | 即插即用,大幅减少参数量,轻量化的同时精度更高效涨点,全网独家改进

💡本篇内容:芒果YOLOv5改进87:轻量化检测头篇:LiteShiftHead 独家原创检测头 | 即插即用,独家新颖更新,大幅减少参数量,轻量化的同时精度高效涨点,全网独家 芒果专栏提出多种原创的轻量化检测头 LiteShiftHead 结构,改进源码教程 | 详情如下🥇 同时本文将演示说清楚二…

Python 和 Go:一文了解

Python 和 Go 各具特色&#xff0c;能够互补。 有一个常见的误解认为 简单&#xff08;simple&#xff09;和 容易&#xff08;easy&#xff09;指的是同一件事。毕竟&#xff0c;如果某样东西易于使用&#xff0c;那么其内在机制必须也简单易懂&#xff0c;对吗&#xff1f;或…

1332多元bfs

/* 多元bfs就是从多个点开始&#xff0c;开始的时候多往初始队列放几个进去 距离数组中最好初始化为-1&#xff1b;然后再起点入队时赋值为0 */ #include<bits/stdc.h> using namespace std; int dx[4]{0,1,0,-1}; int dy[4]{1,0,-1,0}; int f[510][510],dist[510][510];…

math模块篇(五)

文章目录 math.remainder(x, y)math.sumprod(p, q)math.trunc(x)math.ulp(x)math.cbrt(x)math.exp(x)math.exp2(x)math.expm1(x) math.remainder(x, y) math.remainder(x, y) 是 Python 3.8 版本中新增的一个函数&#xff0c;用于计算两个数 x 和 y 相除后的余数。这个函数的行…

Python中的文件读取与保存

1、文件的读取 常用的函数&#xff1a; 1. open()&#xff1a;用于打开文件&#xff0c;可以指定不同的模式&#xff08;读取、写入、追加等&#xff09;来操作文件内容。 2. write()&#xff1a;用于将数据写入文件。 3. close()&#xff1a;用于关闭文件&#xff0c;确保文件…

C++ set 常用部分

文章目录 关键特性定义及初始化一些基本操作查找插入删除清空遍历lower_bound()、upper_bound()set与unordered_set的区别 关键特性 唯一性&#xff1a;Set容器内的元素都是唯一的&#xff0c;每个元素都是不同的有序性&#xff1a;Set容器内的元素总是排序的&#xff08;C中默…

electron+VUE Browserwindow与webview通信

仅做记录 前言&#xff1a; electronVUEVITE框架&#xff0c;用的是VUE3.0 主进程定义&#xff1a;用于接收webview发送的消息 ipcMain.on(MyWebviewMessage, (event, message) > {logger.info(收到webmsg message)//转发给渲染进程}) porelaod/webPreload.js定义 cons…

C语言编译与链接

前言 我们想一个问题&#xff0c;我们写的C语言代码都是文本信息&#xff0c;电脑能直接执行c语言代码吗&#xff1f;肯定不能啊&#xff0c;计算机能执行的是二进制指令&#xff0c;所以将C语言转化为二进制指令需要一段过程&#xff0c;这篇博客讲一下编译与链接&#xff0c;…

跨域问题详解(vue工程中的解决办法)

目录 1. 什么是跨域 2. 如何解决跨域问题 1. 配置request.js 2. 配置vite.config.js 1. 什么是跨域 跨域问题指的是当一个网页的源&#xff08;origin&#xff09;与另一个网页的源不同时&#xff0c;浏览器出于安全考虑&#xff0c;会限制页面中的跨域请求。源是由协议、主…

五种主流数据库:高级分组

除了基本的分组功能之外&#xff0c;GROUP BY 子句还提供了几个高级选项&#xff0c;可以用来实现更复杂的报表功能。 本文比较五种主流数据库实现的高级分组功能&#xff0c;包括 MySQL、Oracle、SQL Server、PostgreSQL 以及 SQLite。 功能MySQLOracleSQL ServerPostgreSQL…

Day26 手撕各种集合底层源码(一)

Day26 手撕各种集合底层源码&#xff08;一&#xff09; 一、手撕ArrayList底层源码 1、概念&#xff1a; ArrayList的底层实现是基于数组的动态扩容结构。 2、思路&#xff1a; 1.研究继承关系 2.研究属性 3.理解创建集合的过程 – 构造方法的底层原理 4.研究添加元素的过程…

vue实现把Ox格式颜色值转换成rgb渐变颜色值(开箱即用)

图示&#xff1a; 核心代码&#xff1a; //将0x格式的颜色转换为Hex格式&#xff0c;并计算插值返回rgb颜色 Vue.prototype.$convertToHex function (colorCode1, colorCode2, amount) {// 确保输入是字符串&#xff0c;并检查是否以0x开头let newCode1 let newCode2 if (t…

关系型数据库mysql(5)存储引擎

目录 一.存储引擎的概念 二. MyISAM 和 InnoDB 2.1MyISAM介绍 2.2MyISAM支持的存储格式 2.2.1静态表&#xff08;固定长度表&#xff09; 2.2.2动态表 2.2.3压缩表 2.3场景举例 2.4.InnoDB 2.4.1场景举例 2.4.2企业选择存储引擎依据 三.查看存储引擎 3.1查看当前数…

IMU预积分【SLAM】

前言 预积分的推导过程比较多&#xff0c;所以这里只记录关键结论。 其实这些公式不太好记忆&#xff0c;因为预积分推导过程的想法来源很巧妙&#xff0c;无法看出物理意义。 预积分定义式&#xff08;必须记住&#xff09; 一切推导的来源&#xff1a; 最好记忆的旋转相对…

c语言教务成绩管理系统1000+

定制魏:QTWZPW,获取更多源码等 目录 题目 代码主函数 教务信息头文件 题目 编写一个C语言程序,实现一个教务成绩管理系统,至少能够管理30条学生信息。其中: 1)学生信息包括:基本信息和成绩信息。 2)基本信息包括:班级,学号,姓名,性别,专业,普通课程选修数…

C++中的STL简介与string类

目录 STL简介 STL的版本 STL的六大组件 string类 标准库中的string类 string类的常用接口 string类对象对容量的操作 size()函数与length()函数 capacity()函数 capacity的扩容方式 reserve()函数 resize()函数 string类对象的操作 push_back()函数 append()函数 operator()函数…

【01-20】计算机网络基础知识(非常详细)从零基础入门到精通,看完这一篇就够了

【01-20】计算机网络基础知识&#xff08;非常详细&#xff09;从零基础入门到精通&#xff0c;看完这一篇就够了 以下是本文参考的资料 欢迎大家查收原版 本版本仅作个人笔记使用1、OSI 的七层模型分别是&#xff1f;各自的功能是什么&#xff1f;2、说一下一次完整的HTTP请求…