写一个esp8266连接阿里云的arduino代码
时间: 2023-03-11 20:59:16 浏览: 154
我们可以使用下面的代码来实现esp8266连接阿里云arduino:#include <ESP8266WiFi.h>
#include <PubSubClient.h>// WiFi设置
const char* ssid = "YourNetworkName";
const char* password = "YourNetworkPassword";// 阿里云设置
const char* mqtt_server = "YourAliYunIoTHost";// 创建WiFi和MQTT客户端实例
WiFiClient espClient;
PubSubClient client(espClient);// 订阅主题
String topic_sub = "YourTopicName";// 定义WiFi连接状态
int status = WL_IDLE_STATUS;void setup() {
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}// 设置WiFi连接
void setup_wifi() {
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid); // 连接到WiFi网络
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());
}// 连接到MQTT服务器
void reconnect() {
// 如果未连接,则尝试重新连接
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// 尝试连接
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// 订阅主题
client.subscribe(topic_sub.c_str());
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// 等待5秒
delay(5000);
}
}
}// 消息回调函数
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println(); // 执行相应的操作
if (String(topic) == topic_sub) {
Serial.print("Changing output state to ");
if(messageTemp == "on"){
Serial.println("on");
}
else if(messageTemp == "off"){
Serial.println("off");
}
}
}
阅读全文