#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
// GPIO 5 D1
#define LED 5
// MQTT Broker
//,,,,
const char *mqtt_broker = "###";//设置MQTT 地址
const char *topic = "esp8266/led";//订阅名称
const char *mqtt_username = "###";//连接用户名
const char *mqtt_password = "####";//密码
const int mqtt_port = 1883;//端口
//创建一个wificlient对象
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
//设置板载LED管脚为输出模式
pinMode(LED_BUILTIN, OUTPUT);
// Set software serial baud to 9600;
//设置软件串口波特率为9600;
Serial.begin(9600);
//以下这两句是建立自动配网最主要的函数
// 建立WiFiManager对象
WiFiManager wifiManager;
// 自动连接WiFi。以下语句的参数是连接ESP8266时的WiFi名称
wifiManager.autoConnect("AutoConnectAP");
// WiFi连接成功后将通过串口监视器输出连接成功信息
Serial.println("");
Serial.print("ESP8266 Connected to ");
Serial.println(WiFi.SSID()); // WiFi名称
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // IP
//connecting to a mqtt broker
//连接MQTT服务器
client.setServer(mqtt_broker, mqtt_port);//
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp8266-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "hello emqx");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
String message;
for (int i = 0; i < length; i++) {
message = message + (char) payload[i]; // convert *byte to string
}
Serial.print(message);
if (message == "on") { digitalWrite(LED_BUILTIN, LOW); } // LED on
if (message == "off") { digitalWrite(LED_BUILTIN, HIGH); } // LED off
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
}
最后修改:2022 年 02 月 21 日
© 允许规范转载