从ESP8266示例更改而来,运行在ESP32-WROOM上,想运行在ESP8266,就改WIFI头文件,arduino需要添加PubSubClient库,具体添加方法看太极创客的教学或者自行百度。Arduino IDE环境搭建不懂的也自行百度。这里用的灯的IO为2号引脚。阿里云设备属性为开关属性。
#include <WiFi.h> //ESP32
//#include <ESP8266WiFi.h> //ESP8266
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "ChinaNet-2C71"; //提供可用的WIFI名
const char* password = "*********"; //提供WIFI密码
/****以下是阿里云设备的信息****/
const char* mqtt_server = "***************************";//服务器
const char* clientId = "***************************";
const char* username = "***************************";
const char* passwd = "***************************";
const char* pubtopic = "***************************"; //发布消息的主题
const char* subtopic = "***************************"; //要订阅的主题
/******定义要用到的变量******/
WiFiClient espClient;
PubSubClient client(espClient);
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int BUILTIN_LED = 2;
void setup_wifi() {
delay(10);
// 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(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
/***接收到服务器数据后调用的中断函数,主要做了串口打印出接收的数据,根据payload的首字符点灯,更新灯的状态到服务器3件事***/
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, HIGH); // 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, LOW); // Turn the LED off by making the voltage HIGH
}
//update the led status to aliyun
snprintf (msg, MSG_BUFFER_SIZE, "{\"params\":{\"PowerSwitch\":%1d}}", digitalRead(BUILTIN_LED));//发布的payload格式根据自己在阿里云建立的设备属性而定
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(pubtopic, msg);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientId, username, passwd )) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(pubtopic, "hello world"); //这句没有意义,可以删除
// ... and resubscribe
client.subscribe(subtopic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
client.setSocketTimeout(30);
client.setKeepAlive(30);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
用MQTT.fx工具调试结果,发送1板子亮灯,发其他则灭灯。这里是在阿里云上建了2台设备,来互相通信的。
阿里云的设备信息直接登陆官网去找,如下,在设备里进去自己的设备后点图中查看按钮,具体如何在阿里云上创建设备教程请自行百度。