nodemcu+DHT11接入阿里物联网平台学习

万物物联 专栏收录该内容
1 篇文章 0 订阅

先感谢:
太极创客DHT11 温度湿度传感器 ESP8266 开发资料
ESP8266接入阿里云物联网平台上传温湿度数据
再上代码

#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
#include <SparkFun_SHTC3.h>
#include <dht11.h>
dht11 DHT11;//定义传感器类型
#define DHT11PIN 2//定义传感器连接引脚。此处的PIN2在NodeMcu8266开发板上对应的引脚是D4
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID         "wifi name"
#define WIFI_PASSWD       "wifi password"


/* 设备的三元组信息*/
#define PRODUCT_KEY       "阿里平台获取"
#define DEVICE_NAME       "阿里平台获取"
#define DEVICE_SECRET     "阿里平台获取"
#define REGION_ID         "cn-阿里平台获取"

/* 线上环境域名和端口号,不需要改 */
#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         "wushuo123|securemode=3,signmethod=hmacsha1,timestamp=132323232|"
// 算法工具: 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\":\"ESP8266\",\"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;

/********************###子函数###********************/
double Fahrenheit(double celsius)
{
  return 1.8 * celsius + 32; //摄氏温度度转化为华氏温度
}
 
double Kelvin(double celsius)
{
  return celsius + 273.15; //摄氏温度转化为开氏温度
}
 


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"); 
    }

    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;
  }
}

void setup() 
{
    /* initialize serial for debugging */
    Serial.begin(115200);
   Serial.println("\n");
  Serial.println("esp8266读取DHT11传感器数值 ");
  Serial.println("串口会分别打印当前湿度(%),当前摄氏度温度,当前华氏度温度和当前开式温度 ");
  Serial.print("DHT11库文件版本: ");
  Serial.println(DHT11LIB_VERSION);
  Serial.println();
    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()
{

  RH=DHT11.humidity;
  T=DHT11.temperature;
  RH_sum+=RH;
  T_sum+=T;
  count+=1;   
  Serial.println(RH+T+RH_sum+T_sum);
  DHT11.read(DHT11PIN); //更新传感器所有信息
 
  Serial.print("当前湿度 (%): ");
  Serial.println((float)DHT11.humidity, 2);
 
  Serial.print("当前温度 (℃): ");
  Serial.println((float)DHT11.temperature, 2);
 
  Serial.print("当前温度 (℉): ");
  Serial.println(Fahrenheit(DHT11.temperature), 2);
 
  Serial.print("当前温度 (K): ");
  Serial.println(Kelvin(DHT11.temperature), 2);
 
  delay(2000);//每两秒打印一次
  if (millis() - lastMs >= 1000)
  {
    lastMs = millis();
    mqttCheckConnect(); 

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

今天买的板子刚到货,之前没了解过物联网,就百度着简单做了做,代码大部分为拼凑,还在研究学习。期望更高的提升~

底下是效果图。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    评论
  • 3
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值