CCC_122:博客只用于学习交流,不涉及任何商业用途,如果有错误之处,欢迎指正。
在上一个博客的基础上 探索ESP8285(2)搭建Windows版MQTT服务器
我们来通过EMQX服务器点亮ESP8285模块上的LED灯。
首先查得ESP8285模块上的LED灯引脚是GPIO4,低电平亮起,所以我们先定义GPIO口
在setup里设置引脚为输出模式
在连接里修改订阅的主题为 /mqtt/test/
在callback函数里修改LED引脚参数
编译上传到ESP8285模块上,接下来测试效果:
打开MQTTBox,连接好服务器,在Payload上输入1,然后按Publish发布信息。
ESP8285模块接收到信息后会自动打开LED。 如果是发送0或者其他的字符,LED灯关闭。
以下是整个测试代码:
#include <ESP8266WiFi.h>#include <PubSubClient.h>#define PIN_LED 4// Update these with values suitable for your network.const char* ssid = "....";const char* password = "....";//const char* mqtt_server = "iot.eclipse.org";const char* mqtt_server = "192.168.1.162";const String macAddress = WiFi.macAddress();//const char* clientID = macAddress.c_str();const char* clientID = "client001";const char* userName = "user001";const char* passWord = "psd001";WiFiClient espClient;PubSubClient client(espClient);long lastMsg = 0;char msg[50];int value = 0;void setup() { pinMode(PIN_LED, OUTPUT); // Initialize the LED pin as an outputSerial.begin(115200);setup_wifi();client.setServer(mqtt_server, 1883);client.setCallback(callback);}void setup_wifi() {delay(10);// We start by connecting to a WiFi networkSerial.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 characterif ((char)payload[0] == '1') {digitalWrite(PIN_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(PIN_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...");// Attempt to connectif (client.connect(clientID,userName,passWord)) {Serial.println("connected");// Once connected, publish an announcement...client.publish("/mqtt/test/", "hello world");// ... and resubscribeclient.subscribe("/mqtt/test/#");} else {Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");// Wait 5 seconds before retryingdelay(5000);}}}void loop() {if (!client.connected()) {reconnect();}client.loop();// long now = millis();
// if (now - lastMsg > 2000) {
// lastMsg = now;
// ++value;
// snprintf (msg, 75, "hello world #%ld", value);
// Serial.print("Publish message: ");
// Serial.println(msg);
// client.publish("outTopic", msg);
// }}