概述
两个模块,一个模块为按键,另一个模块为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());
}
最后
以上就是不安雨为你收集整理的oneNet之MQTT按键控制LED的全部内容,希望文章能够帮你解决oneNet之MQTT按键控制LED所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复