ESP8266 + DHT11 温湿度监控+手机App查看

Scroll Down

首先注册 电灯科技账号

相关文档: https://diandeng.tech/doc/temperature-and-humidity-sensor

image.png

添加设备后, 注意数据键名
温度: humi
湿度: temp
其他随意即可

 
#define BLINKER_WIFI
// 传感器设备
#define BLINKER_MIOT_SENSOR
#include <DHT.h>
 
#include <Blinker.h>
 
#define DHTTYPE DHT11
BlinkerNumber HUMI("humi");
BlinkerNumber TEMP("temp");
 
#define DHTPIN 2 
DHT dht(DHTPIN, DHTTYPE);
// 温度读取PIN口
 
char auth[] = "*********"; // 这里你的 key
char ssid[] = "Xiaomi_C0AC";
char pswd[] = "12345678";
 
// 温度
int humidity;
// 湿度
int temperature;
 
 
int humi_read = 0, temp_read = 0;
 
void setup()
{
    // 初始化串口,并开启调试信息
    Serial.begin(115200);
 
    // 初始化blinker
    Blinker.begin(auth, ssid, pswd);
 
    // 响应
    BlinkerMIOT.attachQuery(miotQuery);
 
    // 心跳
    Blinker.attachHeartbeat(heartbeat);
 
    // 初始化存储
    Blinker.attachDataStorage(dataStorage);
}
 
void loop()
{
    Blinker.run();
    // 设置温湿度
    set_humi_and_temp();
    Blinker.delay(2000);
}

void set_humi_and_temp() {
  int h = dht.readHumidity();
    int t = dht.readTemperature();
    Serial.print("当前温度 : ");
    Serial.println(h);
    Serial.print("当前湿度 : ");
    Serial.println(t);
    if (isnan(h) || isnan(t))
    {
        BLINKER_LOG("Failed to read from DHT sensor!");
    }
    else
    {
        humi_read = h;
        temp_read = t;
    }
}
 
/**
 * 心跳
 */
void heartbeat() 
{
    HUMI.print(humi_read);
    TEMP.print(temp_read);
}
/**
 * 数据存储
 */
void dataStorage()
{
    Blinker.dataStorage("temp", temp_read);
    Blinker.dataStorage("humi", humi_read);
}
 
/**
 * 查询
 */
void miotQuery(int32_t queryCode)
{
 
    BLINKER_LOG("MIOT Query codes: ", queryCode);
 
    switch (queryCode)
    {
    case BLINKER_CMD_QUERY_PM25_NUMBER:
        BLINKER_LOG("MIOT Query PM25");
        BlinkerMIOT.pm25(20);
        BlinkerMIOT.print();
        break;
    // 查询湿度属性 BLINKER_CMD_QUERY_HUMI_NUMBER
    case BLINKER_CMD_QUERY_HUMI_NUMBER:
        BLINKER_LOG("MIOT Query HUMI");
        BlinkerMIOT.humi(humidity);
        BlinkerMIOT.print();
        break;
    // 查询温度属性 BLINKER_CMD_QUERY_TEMP_NUMBER
    case BLINKER_CMD_QUERY_TEMP_NUMBER:
        BLINKER_LOG("MIOT Query TEMP");
        BlinkerMIOT.temp(temperature);
        BlinkerMIOT.print();
        break;
    default:
        BlinkerMIOT.temp(temperature);
        BlinkerMIOT.humi(humidity);
        BlinkerMIOT.pm25(-1);
        BlinkerMIOT.co2(-1);
        BlinkerMIOT.print();
        break;
    }
}