esp8266代码示例
时间: 2023-10-07 08:11:55 浏览: 101
以下是一个ESP8266的Arduino示例代码,其中使用了WiFi库和MQTT库来连接到WiFi网络并发布/订阅MQTT消息:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi网络信息
const char* ssid = "你的WiFi名称";
const char* password = "你的WiFi密码";
// MQTT服务器信息
const char* mqtt_server = "mqtt服务器地址";
const int mqtt_port = 1883;
const char* mqtt_username = "mqtt用户名";
const char* mqtt_password = "mqtt密码";
// 订阅主题
const char* subscribe_topic = "你的订阅主题";
// 发布主题
const char* publish_topic = "你的发布主题";
// WiFi客户端
WiFiClient wifi_client;
// MQTT客户端
PubSubClient mqtt_client(wifi_client);
// 连接WiFi网络
void connectWiFi() {
Serial.print("连接到WiFi网络...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("成功");
}
// 连接MQTT服务器
void connectMQTT() {
Serial.print("连接到MQTT服务器...");
mqtt_client.setServer(mqtt_server, mqtt_port);
mqtt_client.setCallback(mqttCallback);
while (!mqtt_client.connected()) {
if (mqtt_client.connect("ESP8266", mqtt_username, mqtt_password)) {
mqtt_client.subscribe(subscribe_topic);
Serial.println("成功");
} else {
Serial.print("失败,错误代码: ");
Serial.println(mqtt_client.state());
delay(2000);
}
}
}
// MQTT消息回调函数
void mqttCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("收到消息 [");
Serial.print(topic);
Serial.print("]: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
// 发布MQTT消息
void publishMQTT(char* message) {
mqtt_client.publish(publish_topic, message);
}
void setup() {
Serial.begin(9600);
connectWiFi();
connectMQTT();
}
void loop() {
mqtt_client.loop();
publishMQTT("Hello World!");
delay(5000);
}
阅读全文