mqtt+ardunio+esp8266开发(不含mqtt服务器部署)

总流程:
在这里插入图片描述
图片来源:一个大佬id:liefyuan

(特此鸣谢很多大佬,他们的文章给与我很多帮助)

第一步 软件硬件准备

1.ESP8266 CP2102物联网模块

这是我淘的板子
2.公对母杜邦线若干
3.arduino uno开发板或者同类开发板。
软件要求:
arduino ide
实物图:在这里插入图片描述
引脚连接:
ESP8266 ------UNO
VCC-----------3.3v
GND----------GND
RX-------------TX PIN2 (用的SoftWareSerialExample)
TX-------------RX PIN3(用的SoftWareSerialExample)

之前用的01TXRX结果一直不行,没想到软串口通信成功解决。

pubsub库可与ESP8266开发板/库单独一起使用。
步骤如下:
要安装ESP8266开发板(使用Arduino 1.6.4+):
-在“文件->首选项->附加开发板管理器网址”下添加以下第三网址: http://arduino.esp8266.com/stable/package_esp8266com_index.json
-打开“工具->板->板管理器”,然后为ESP8266单击“安装”
-在“工具->开发板”中选择ESP8266

第一步 配网 + 连接

来!我们用库!!!!MQTT的库有很多,本文将采用PubSubClient库. 此库可以在Arduino IDE的库管理器中找到。工具->管理库->找到PubSubClient根据自己想要的版本下载,之后打开实例
在这里插入图片描述
(1)联网

A、ssid为自己WIFI无线网络的名称,password为WIFI无线网络密码。
在这里插入图片描述

B、利用WiFi.begin(ssid, password);进行连接网络,此函数为库中封装函数,传入两个关键值进行连接。

C、进行联网随之取出连接状态进行判断while (WiFi.status() != WL_CONNECTED) {…}

(2)连接MQTT服务器
A、定义自己的服务器地址

B、client.setServer(mqtt_server, 1883); 此封装函数用来连接MQTT服务器,1883是默认的MQTT端口

C、client.setCallback(callback);设定回调方式,当ESP8266收到订阅消息时会调用此方法

下面是软串口代码:10和11就是开发板的RX和TX 连接MQTT与ardunio

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.println("HELLO!JINYU");

// set the data rate for the SoftwareSerial port
mySerial.begin(115200);
mySerial.println("JINYU");
}

void loop() // run over and over
{
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
}

第三步 订阅和发布

(3)订阅和发布
A、实例化
WiFiClient espClient;
PubSubClient client(espClient);
B、定义订阅Topic :
const char* TOPIC = “”;
或者:client.publish(“outTopic”, “hello world”);//发布主题和内容
client.subscribe(“inTopic”);//订阅服务器上的inTopic主题内容。
C、串口监视
在这里插入图片描述

最后附上总的代码:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "JINYU";
const char* password = "15034755486";
const char* mqtt_server = "123.57.133.**";//这里就是部署MQTT服务器的服务器地址

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

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

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* 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 character
  if ((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 acive 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 reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } 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 > 20000) {//延时
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }

错误反思:
1、我引脚EN接了VCC不可取正常VCC接VCC
2、如果用自己热点别用中文容易出错
3、mqtt_server带了:8080
4、RX和TX一定要注意顺序别混
5、0 1 有时无法使用,需要软串口通讯

如果用lot,请参考
id:爱学习的素丸子—只要会用电脑就能看懂的物联网教程(阿里云+esp8266+微信小程序)

我的订阅调试信息
在这里插入图片描述
整理结束

写在最后:学习永无止境,我永远是个弟弟hhhh

发布了9 篇原创文章 · 获赞 3 · 访问量 605

猜你喜欢

转载自blog.csdn.net/weixin_45149775/article/details/105694704
今日推荐