引用库
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
变量声明
const char* mqtt_server = "140.238.60.127";
const char* client_id = "test-phvb01"; // 标识当前设备的客户端编号
const char* mqtt_user = "mqtt"; //MQTT用户名
const char* mqtt_password = "phphph"; //MQTT密码
const char* wakeup = "wakeup"; //TOPIC主题
WiFiClient espClient;
PubSubClient client(espClient);
主函数注册
//初始化
void setup()
{
WiFi.mode(WIFI_STA);
Serial.begin(115200);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("MQTT connecting...");
if (client.connect(client_id, mqtt_user, mqtt_password)) {
Serial.println("MQTT connect success.");
client.subscribe(wakeup); //订阅wakeup主题。
} else {
delay(5000);
}
}
}
//主循环
void loop{
client.publish(hello, "Hello MQTT!"); //循环向hello主题发送“Hello MQTT!”
client.loop();
}
回调函数 Callback(接收消息)
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") {
for(int x=1;x<=56;x++){ //当wakeup收到ON时,GPIO15翻转电平56次。
digitalWrite(15, HIGH);
delay(90);
digitalWrite(15, LOW);
delay(90);
}
} // LED on
Serial.println();
Serial.println("-----------------------");
}