eso8266基于点灯科技平台智能插座代码
时间: 2023-06-13 12:07:31 浏览: 146
很好,基于点灯科技平台的智能插座代码如下所示:
```
/*
* 该代码是基于点灯科技平台开发的智能插座代码
* 作者:点灯科技
* 时间:2022年1月20日
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi信息
const char* ssid = "你的WiFi名称";
const char* password = "你的WiFi密码";
// MQTT信息
const char* mqtt_server = "你的MQTT服务器地址";
const char* mqtt_username = "你的MQTT用户名";
const char* mqtt_password = "你的MQTT密码";
const char* mqtt_topic = "你的MQTT主题";
// LED灯信息
const int ledPin = 2;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
delay(10);
// 连接WiFi
Serial.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");
// 连接MQTT服务器
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
Serial.println("connected");
client.subscribe(mqtt_topic);
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message received: ");
Serial.println(topic);
Serial.print("Payload: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '1') {
digitalWrite(ledPin, HIGH);
client.publish(mqtt_topic, "ON");
} else {
digitalWrite(ledPin, LOW);
client.publish(mqtt_topic, "OFF");
}
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
Serial.println("connected");
client.subscribe(mqtt_topic);
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
```
请注意,你需要根据自己的 WiFi 和 MQTT 信息修改代码中的相关信息。此外,这是一个基础的智能插座代码,你可以根据自己的需求进行扩展和修改。
阅读全文