oneNet之MQTT按键控制LED

两个模块,一个模块为按键,另一个模块为led,暂时先连上MQTT

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid     = "Xiaomi_1EDE";       // 连接 WiFi名 ,修改为自己的WiFi名                                      
const char* password = "1234567890";          // 连接 WiFi密码,修改为自己的WiFi密码

const char *mqtt_server = "183.230.40.39";  //OneNet MQTT接入服务器IP,按开发文档说明设置
const uint16_t mqttPort = 6002;   //端口号

const char *productId = "375006";  //产品id
const char *apiKey = "aFKcWTrm6VJfgfF1pQqW2=NWDck=";     //鉴权信息
const char *deviceId = "633517037";   //设备id

const char *topic ="esp8266LED";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqttPort);
  client.setCallback(callback);
}

void loop() {
  ESP.wdtFeed();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  delay(2000);
}

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 character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.println("Connect to OneNet MQTT...");
    /**
        * 参考OneNet mqtt连接报文
        * ClientIdentifier: 创建设备时得到的设备ID
        * UserName: 注册产品时,平台分配的产品ID
        * UserPassword: 为设备的鉴权信息(即唯一设备编号,SN),或者为apiKey
    */   
    if (client.connect(deviceId,productId,apiKey)) {
      Serial.println("connect success!");
      client.subscribe(topic);
    } else {
      Serial.print("connect fail!");
      Serial.println(" try again in 5 seconds");
      delay(5000);   // Wait 5 seconds before retrying
    }
  }
}

void setup_wifi() {
  delay(100);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  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());
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值