感谢qq_27158179,参看他的文章使我少踩太多坑。https://blog.csdn.net/qq_27158179/article/details/90549494
————————————————
正在学习ESP8266,使用的是一块wemos d1 r1的开发板。由于对SDK不太了解,所以采用了MQTT/TCP的通讯方式连接阿里云方案。
面板板*1
wemos d1 r1 1
数据线1
接线图如下:
DHT11的VCC和GND经面包板接到开发板的3.3V和GND上。DHT11上的DATA针脚经面包板插到开发板上的GPIO14上(期间曾将该针脚接到模拟口A0上,但是串口监视一直报TIMEOUT,没有查出原因作罢)。
在IDE的库文件管理中搜寻PubSubClient.h和ArduinoJson.h库文件并安装
每个人的库文件位置都不一样,我的在C盘,有的在arduino的安装目录下,不清楚的可以使用电脑搜索功能。
// MQTT_MAX_PACKET_SIZE : Maximum packet size
#define MQTT_MAX_PACKET_SIZE 1024 //数字改成大于等于1024
// MQTT_KEEPALIVE : keepAlive interval in Seconds
#define MQTT_KEEPALIVE 60 //数字改成大于等于60
全部程序
#include
/* 依赖 PubSubClient 2.4.0 */
#include
/* 依赖 ArduinoJson 5.13.4 */
#include
/* Use DHT_sensor_library_for_ESPx */
#include "DHTesp.h"
//还没懂下面这段的意思
#ifdef ESP32
#pragma message(THIS EXAMPLE IS FOR ESP8266 ONLY!)
#error Select ESP8266 board.
#endif
DHTesp dht;
//#define SENSOR_PIN 13 //这个是定义红外热式传感器的针脚
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID "***" //自家的WiFi账号替换星号
#define WIFI_PASSWD "***" //自家的WiFi密码替换星号
/* 设备证书信息*/
#define PRODUCT_KEY "***" //阿里云上设备的ProductKey
#define DEVICE_NAME "***" //阿里云上设备的DeviceName
#define DEVICE_SECRET "***" //阿里云上设备的DeviceSecret
#define REGION_ID "cn-shanghai" //小白我在上海
/* 线上环境域名和端口号,连接阿里云都一样,不需要改 */
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT 1883
#define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY
#define CLIENT_ID "esp8266|securemode=3,timestamp=1234567890,signmethod=hmacsha1|"
// MQTT连接报文参数,请参见MQTT-TCP连接通信文档,文档地址:https://help.aliyun.com/document_detail/73742.html
// 加密明文是参数和对应的值(**clientId**esp8266**devicename**DeviceName**productKey**ProductKey**timestamp**1234567890)按字典顺序拼接,加粗的不变,替换不加粗的部分
// 密钥是设备的DeviceSecret
#define MQTT_PASSWD "6D6C***5AFA5" //阿里的计算工具有问题,害的我出现err:-1报错。可以参看https://blog.csdn.net/qq_27158179/article/details/90549494中5.3
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
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);
}
void wifiInit()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("espClient [");
client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */
client.setCallback(callback);
}
void mqttCheckConnect()
{
while (!client.connected())
{
Serial.println("Connecting to MQTT Server ...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("MQTT Connected!");
}
else
{
Serial.print("MQTT Connect err:");
Serial.println(client.state());
delay(5000);
}
}
}
void mqttIntervalPost()
{
char param[32];
char jsonBuf[128];
// delay(dht.getMinimumSamplingPeriod());
int humidity = dht.getHumidity();
int temperature = dht.getTemperature();
sprintf(param, "{\"mhumi\":%d,\"mtemp\":%d}", humidity, temperature);
// sprintf(param, "{\"mtemp\":%d}", temperature);
sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
Serial.println(jsonBuf);
boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
Serial.print("publish:0 失败;1成功");
Serial.println(d);
}
void setup()
{
Serial.begin(115200);
Serial.println("Demo Start");
Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)\tHeatIndex (C)\t(F)");
String thisBoard = ARDUINO_BOARD;
Serial.println(thisBoard);
dht.setup(14, DHTesp::DHT11); /*这个一定记得改成自己连接的针脚,Connect DHT sensor to GPIO 14*/
wifiInit();
}
// the loop function runs over and over again forever
void loop()
{
if (millis() - lastMs >= 5000)
{
lastMs = millis();
mqttCheckConnect();
/* 上报消息心跳周期 */
mqttIntervalPost();
}
client.loop();
// if (digitalRead(SENSOR_PIN) == HIGH) {
// Serial.println("Motion detected!");
// delay(2000);
// }
// else {
// Serial.println("Motion absent!");
// delay(2000);
// }
delay(dht.getMinimumSamplingPeriod());
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
Serial.print(dht.getStatusString());
Serial.print("\t");
Serial.print(humidity, 1);
Serial.print("\t\t");
Serial.print(temperature, 1);
Serial.print("\t\t");
// Serial.print(dht.toFahrenheit(temperature), 1);
// Serial.print("\t\t");
Serial.println(dht.computeHeatIndex(temperature, humidity, false), 1);
// Serial.print("\t\t");
// Serial.println(dht.computeHeatIndex(dht.toFahrenheit(temperature), humidity, true), 1);
delay(2000);
}
注册我就不介绍了。
主要是先设置产品,然后再设置设备,关键是获得程序所需要的ProductKey、DeviceName、DeviceSecret三个重要内容.
顺便说一下,阿里云的IOT studio可以直接设计一些web/移动端的显示界面,对于小白我还是蛮惊喜的!
最后祝enjoy!