首先我们需要下载下面的依赖库
https://github.com/legenddcr/aliyun-mqtt-arduino
https://github.com/rweather/arduinolibs
这个我已经打包放到lib文件夹里面去了,我们只需要解压放到arduino的lib库里去
默认在C盘的文档里面
然后我们修改PubSubClient
库的连接参数。这里改成60
下面我们把测试代码烧进去
#include
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "aliyun_mqtt.h"
// GPIO 13, D7 on the Node MCU v3
#define SENSOR_PIN 13
#define WIFI_SSID "wifi名字"
#define WIFI_PASSWD "wifi密码"
#define PRODUCT_KEY "a1NRzHXlTTp"
#define DEVICE_NAME "Band"
#define DEVICE_SECRET "563221c763c3cbd474a4180afb775948"
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"%s\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
#define ALINK_TOPIC_PROP_POSTRSP "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post_reply"
#define ALINK_TOPIC_PROP_SET "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/service/property/set"
#define ALINK_METHOD_PROP_POST "thing.event.property.post"
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void initWifi(const char *ssid, const char *password)
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("WiFi does not connect, try again ...");
delay(3000);
}
Serial.println("Wifi is connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
payload[length] = '\0';
Serial.println((char *)payload);
if (strstr(topic, ALINK_TOPIC_PROP_SET))
{
StaticJsonBuffer<100> jsonBuffer;
JsonObject &root = jsonBuffer.parseObject(payload);
if (!root.success())
{
Serial.println("parseObject() failed");
return;
}
}
}
void mqttCheckConnect()
{
// Serial.println(mqttClient);
Serial.println(PRODUCT_KEY);
Serial.println(DEVICE_NAME);
Serial.println(DEVICE_SECRET);
while (!connectAliyunMQTT(mqttClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET,"cn-shanghai"))
{
}
Serial.println("MQTT connect succeed!");
// client.subscribe(ALINK_TOPIC_PROP_POSTRSP);
mqttClient.subscribe(ALINK_TOPIC_PROP_SET);
Serial.println("subscribe done");
}
void mqttIntervalPost()
{
char param[32];
char jsonBuf[128];
sprintf(param, "{\"HeartRate\":%d}", digitalRead(13));
sprintf(jsonBuf, ALINK_BODY_FORMAT, ALINK_METHOD_PROP_POST, param);
Serial.println(jsonBuf);
mqttClient.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
}
void setup()
{
pinMode(SENSOR_PIN, INPUT);
/* initialize serial for debugging */
Serial.begin(115200);
Serial.println("Demo Start");
initWifi(WIFI_SSID, WIFI_PASSWD);
mqttClient.setCallback(callback);
}
// the loop function runs over and over again forever
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
/* Post */
mqttIntervalPost();
}
mqttClient.loop();
unsigned int WAIT_MS = 60000;
if (digitalRead(SENSOR_PIN) == HIGH)
{
Serial.println("Motion detected!");
}
else
{
Serial.println("Motion absent!");
}
delay(WAIT_MS); // ms
Serial.println(millis() / WAIT_MS);
}
然后我们就可以正确使用了,我遇到下面这两个问题
1.sha256.h 文件找不到,这个需要自己去下载这个库,然后找到我们需要的部分放到arduino里面就可以了。
2.一直连接不上,这个修改一下PubSubClient库的连接参数也成功解决
最终代码
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "aliyun_mqtt.h"
/*
* esp8266连接阿里云平台
* 作者: 小游
* 参考demo: https://github.com/legenddcr/aliyun-mqtt-arduino/blob/master/examples/uno/uno.ino
* 完成时间: 2020/10/17
*/
// wifi账号密码
#define WIFI_SSID "xiaoyou"
#define WIFI_PASSWD "1806040103"
// 阿里云设备的必要信息
#define PRODUCT_KEY "a1NRzHXlTTp"
#define DEVICE_NAME "Band"
#define DEVICE_SECRET "563221c763c3cbd474a4180afb775948"
// 下面这个密码需要通过sha256加密获得 加密网址http://iot-face.oss-cn-shanghai.aliyuncs.com/tools.htm 秘钥就是DEVICE_SECRET,
// 加密的明文是下面这个,自己记得去掉[] 如果是自己的自行替换[]里面的内容
//clientId[Band]deviceName[Band]productKey[a1NRzHXlTTp]timestamp[23668]
#define TIMESTAMP "23668"
#define MQTT_PASSWORD "dcf3dc9d40317ade161a42934eefe2ec4e0e4a2398dcd44798ae0bf833738e8d"
// 阿里云自带的订阅链接,这里我们用不到
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
//#define ALINK_TOPIC_PROP_POSTRSP "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post_reply"
//#define ALINK_TOPIC_PROP_SET "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/service/property/set"
// wifi的连接和mqtt的连接端
WiFiClient espClient;
PubSubClient mqttClient(espClient);
// 初始化wifi连接
void initWifi(const char *ssid, const char *password)
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
// 不断检测是否连接wifi是否成功
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("WiFi does not connect, try again ...");
delay(3000);
}
// 打印出wifi的ip地址
Serial.println("Wifi is connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// 检查mqtt的连接状态
void mqttCheckConnect()
{
// 判断是否连接
while (!mqttClient.connected())
{
// 如果连接失败就自动重连
Serial.println(F("Connecting to Aliyun IoT ..."));
// 设置更据我们获取到的密码进行连接
if (connectAliyunMQTTWithPassword(mqttClient, MQTT_PASSWORD))
{
Serial.println("[MQTT Connected]");
}
else
{
// 如果连接失败就尝试5秒后重连
Serial.print(F("[MQTT Connect FAILED] [rc = "));
Serial.print(mqttClient.state());
Serial.println(F(": retrying in 5 seconds]"));
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// mqtt发送数据
void mqttSendData(String HeartRate,String SystolicPressure,String DiastolicPressure)
{
// 设置参数
String payload = "{";
payload += "\"HeartRate\":";
payload += HeartRate;
payload += ",\"SystolicPressure\":";
payload += SystolicPressure;
payload += ",\"DiastolicPressure\":";
payload += DiastolicPressure;
payload += "}";
// 设置我们需要发送的数据
String jsonData = F("{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":");
jsonData += payload;
jsonData += F("}");
//吧json字符串转换为数组数据
char alinkData[256];
jsonData.toCharArray(alinkData, 256);
// mqtt发布数据
mqttClient.publish(ALINK_TOPIC_PROP_POST, alinkData);
Serial.println(alinkData);
}
// 程序初始化
void setup()
{
// 设置波特率,连接wifi,以及设置mqtt的基本参数
Serial.begin(9600);
Serial.println("Demo Start");
initWifi(WIFI_SSID, WIFI_PASSWD);
mqttPrepare(TIMESTAMP, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET);
}
// 程序循环
void loop()
{
// 检查mqtt的连接状态
mqttCheckConnect();
// 这里相当于mqtt的心跳包
mqttClient.loop();
// 监听串口,判断串口是否有数发送过来
if(Serial.available()){
//开始读取数据
// 注意 双引号引起来的都是字符串常量,单引号引起来的都是字符常量, 我们这里需要要用单引号
String data = Serial.readStringUntil('e');
String h = data.substring(7,10);
String l = data.substring(11,14);
String heart = data.substring(15,18);
// 打印读取到的数据
Serial.print("getHardData:");
Serial.println(data);
// mqtt数据上报
mqttSendData(heart,h,l);
}
delay(100);
}