路虽远 行则将至

Lee


  • 主页
  • 归档
  • 分类
  • 标签
  •   

站点访客数   人

站点浏览量   次

本页浏览量   次

© 2024 辣辣辣白菜

Theme Typography by Makito

Proudly published with Hexo

Arduino下ESP8266的MQTT

Posted at 2021-09-22 Coding  ESP8266 

引用库

#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("-----------------------");
}

공유하기 

 이전 포스트: AdafruitGFX显示库设置更多字体大小 다음 포스트: ESP8266的Web配网和强制门户 

站点访客数   人

站点浏览量   次

本页浏览量   次

© 2024 辣辣辣白菜

Theme Typography by Makito

Proudly published with Hexo