ESP8266-Arduino编程实例-DHT12温度湿度传感器驱动

DHT12温度湿度传感器驱动

1、DHT12介绍

DHt12是经典DHT11温湿度传感器的升级版,完全向下兼容,精度更高,增加了I2C接口。有如下特性:

  • 紧凑的尺寸
  • 低功耗
  • 低电压操作
  • 标准 I2C 和 1 线接口。
  • 感应范围
    • 温度:-20~+60℃
    • 湿度:20-95 RH
  • 湿度:
    • 分辨率:0.1%RH
    • 重复:-+ 1%RH
    • 精度 25C @ -+5RH
  • 温度:
    • 分辨率:0.1C
    • 重复:-+0.2C
    • 精度:25C@-+0.5C
  • 电源:DC 2.7-5.5V
  • 正常电流1mA
  • 待机电流 60uA
  • 采样周期:> 2 秒

在这里插入图片描述

2、硬件准备

  • ESP8266 NodeMCU开发板一块
  • SHT21传感器模块一个
  • 面板板一个
  • 杜邦线若干
  • 数据线一条

硬件接线如下:

传感器引脚 ESP8266开发板引脚
Vin 5v
Gnd Gnd
SCL D1
SDA D2

3、软件准备

  • Arduino IDE或VSCode + PlatformIO

在前面的文章中,对如何搭建ESP8266开发环境做了详细的介绍,请参考:

ESP8266 NodeMCU的引脚介绍在前面的文章中做了详细的介绍,请参考:

4、代码实现

本次实例使用DHT12的驱动库如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "Arduino.h"

#include <DHT12.h>

// Set dht12 i2c comunication on default Wire pin
DHT12 dht12;

void setup()
{
Serial.begin(112560);
// Start sensor handshake
dht12.begin();
}

int timeSinceLastRead = 0;

void loop()
{
// Report every 2 seconds.
if(timeSinceLastRead > 2000) {
// Reading temperature or humidity takes about 250 milliseconds!
// Read temperature as Celsius (the default)
float t12 = dht12.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f12 = dht12.readTemperature(true);
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h12 = dht12.readHumidity();

bool dht12Read = true;
// Check if any reads failed and exit early (to try again).
if (isnan(h12) || isnan(t12) || isnan(f12)) {
Serial.println("Failed to read from DHT12 sensor!");

dht12Read = false;
}

if (dht12Read){
// Compute heat index in Fahrenheit (the default)
float hif12 = dht12.computeHeatIndex(f12, h12);
// Compute heat index in Celsius (isFahreheit = false)
float hic12 = dht12.computeHeatIndex(t12, h12, false);
// Compute dew point in Fahrenheit (the default)
float dpf12 = dht12.dewPoint(f12, h12);
// Compute dew point in Celsius (isFahreheit = false)
float dpc12 = dht12.dewPoint(t12, h12, false);


Serial.print("DHT12=> Humidity: ");
Serial.print(h12);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t12);
Serial.print(" \*C ");
Serial.print(f12);
Serial.print(" \*F\t");
Serial.print(" Heat index: ");
Serial.print(hic12);
Serial.print(" \*C ");
Serial.print(hif12);
Serial.print(" \*F");
Serial.print(" Dew point: ");
Serial.print(dpc12);
Serial.print(" \*C ");
Serial.print(dpf12);
Serial.println(" \*F");
}
timeSinceLastRead = 0;
delay(100);
timeSinceLastRead += 100;

}

文章来源: https://iotsmart.blog.csdn.net/article/details/126458848