首先我们将导入 ESP8266WiFi 和 PubSubClient 库,ESP8266WiFi 库能够将 ESP8266 连接到 Wi-Fi 网络,PubSubClient 库能使 ESP8266 连接到 MQTT 服务器发布消息及订阅主题。
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
复制代码
设置 Wi-Fi 名称和密码,以及 MQTT 服务器连接地址和端口
- const char *ssid = "name"; // Enter your WiFi name
- const char *password = "pass"; // Enter WiFi passwordconst char *mqtt_broker = "broker.emqx.io";const int mqtt_port = 1883;
复制代码
打开一个串行连接,以便于输出程序的结果并且连接到 Wi-Fi 网络
- <blockquote>// Set software serial baud to 115200;
复制代码设置 MQTT 服务器,并编写回调函数,同时将连接信息打印到串口监视器上
- client.setServer(mqtt_broker, mqtt_port);
- client.setCallback(callback);
- while (!client.connected()) {
- Serial.println("Connecting to public emqx mqtt broker.....");
- if (client.connect("esp8266-client")) {
- Serial.println("Public emqx mqtt broker connected");
- } else {
- Serial.print("failed with state ");
- Serial.print(client.state());
- delay(2000);
- }
- }
- void callback(char *topic, byte *payload, unsigned int length) {
- Serial.print("Message arrived in topic: ");
- Serial.println(topic);
- Serial.print("Message:");
- for (int i = 0; i < length; i++) {
- Serial.print((char) payload[i]);
- }
- Serial.println();
- Serial.println("-----------------------");
- }
复制代码
MQTT 服务器连接成功后,ESP8266 将向 MQTT 服务器发布消息和订阅主题
- // publish and subscribe
- client.publish("esp8266/test", "hello emqx");
- client.subscribe("esp8266/test");
复制代码
将主题名称打印到串行端口,然后打印收到消息的每个字节
- void callback(char *topic, byte *payload, unsigned int length) {
- Serial.print("Message arrived in topic: ");
- Serial.println(topic);
- Serial.print("Message:");
- for (int i = 0; i < length; i++) {
- Serial.print((char) payload[i]);
- }
- Serial.println();
- Serial.println("-----------------------");
- }
复制代码