ESP8266接入阿里云物联网平台上传DHT11检测的温湿度数据

参照:https://blog.zeruns.tech/archives/530.html    这位大佬提供了SHTC3检测数据。手头只有dht11,于是做了些许修改。对应硬件

 dht11的输出对应esp8266 nodeMCU的D1端口。

程序源码:

#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
#include <SparkFun_SHTC3.h>
#include <DHT.h>        //调用DHT库

/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID         "WIFI名称"
#define WIFI_PASSWD       "WIFI密码"


/* 设备的三元组信息*/
#define PRODUCT_KEY       "阿里云设备key"
#define DEVICE_NAME       "阿里云设备名,自己定义的"
#define DEVICE_SECRET     "阿里云提供"
#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         "dht11|securemode=3,timestamp=1234567890,signmethod=hmacsha1|"
// 算法工具: http://iot-face.oss-cn-shanghai.aliyuncs.com/tools.htm 进行加密生成password
// password教程 https://www.yuque.com/cloud-dev/iot-tech/mebm5g
#define MQTT_PASSWD       "阿里云系统生成,参考大佬"

#define ALINK_BODY_FORMAT         "{\"id\":\"dht11\",\"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;
float RH,T,RH_sum,T_sum;
unsigned char count=0;
WiFiClient espClient;
PubSubClient  client(espClient);
//SHTC3 mySHTC3;
DHT dht(D1,DHT11);      //设置Data引脚所接IO口和传感器类型


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);   //连接WiFi
    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];
    sprintf(param, "{\"CurrentTemperature\":%f}",T_sum/count);
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    Serial.println(jsonBuf);
    boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
    if(d){
      Serial.println("publish Temperature success"); 
    }else{
      Serial.println("publish Temperature fail"); 
    }
    //https://blog.zeruns.tech   
    sprintf(param, "{\"CurrentHumidity\":%f}",RH_sum/count);
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    Serial.println(jsonBuf);
    d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
    if(d){
      Serial.println("publish Humidity success"); 
    }else{
      Serial.println("publish Humidity fail"); 
    }
}

void errorDecoder(SHTC3_Status_TypeDef message) // The errorDecoder function prints "SHTC3_Status_TypeDef" resultsin a human-friendly way
{
  switch(message)
  {
    case SHTC3_Status_Nominal : Serial.print("Nominal"); break;
    case SHTC3_Status_Error : Serial.print("Error"); break;
    case SHTC3_Status_CRC_Fail : Serial.print("CRC Fail"); break;
    default : Serial.print("Unknown return code"); break;
  }
}
//https://blog.zeruns.tech
void setup() 
{
    /* initialize serial for debugging */
    Serial.begin(115200);
    dht.begin();   
    Serial.println("Demo Start");
    wifiInit();
    //Wire.begin(D5,D6);           //初始化Wire(IIC)库
    unsigned char i=0;
   // errorDecoder(mySHTC3.begin());
}


// the loop function runs over and over again forever
void loop()
{
  delay(1000);                  //延时1000毫秒
  //SHTC3_Status_TypeDef result = mySHTC3.update();
//  if(dht.lastStatus == DHT11_Status_Nominal)   //判断SHTC3状态是否正常
 // {
    float RH = dht.readHumidity();   //读取湿度数据
    float T = dht.readTemperature();//读取温度数据
    RH_sum+=RH;
    T_sum+=T;
    count+=1;                
//  }else{
 //   Serial.print("Update failed, error: ");
   // errorDecoder(dht.lastStatus); //输出错误原因
   // Serial.println();
 // }
  Serial.print("Humidity:");  //向串口打印 Humidity:
  Serial.print(RH);           //向串口打印湿度数据
  Serial.print("%");
  Serial.print("  Temperature:");
  Serial.print(T);            //向串口打印温度数据
  Serial.println("C"); 
  Serial.println("https://blog.zeruns.tech");
  if (millis() - lastMs >= 30000)
  {
    lastMs = millis();
    mqttCheckConnect(); 

    /* 上报 */
    mqttIntervalPost();
    count=0;
    RH_sum=0;
    T_sum=0;
  }
  client.loop();
}

需先安装 PubSubClientArduinoJsonSparkFun SHTC3这三个库。这三个库不是 Arduino IDE 内置的库文件,需要先点击项目 → 加载库 → 管理库进入库管理器,搜索安装。

PubSubClient.h文件需要相应的修改,参考https://blog.zeruns.tech/archives/530.html

效果图

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值