Arduino板的DHT11温湿度传感器使用

     刚刚接触到arduino板,在使用dht11传感器测量温度和湿度时遇到的最大困难并不是代码的的书写,而是头文件的导入和连接的方法。这里就把自己解决的过程做一下总结。

    因为DHT的头文件在IDE默认的版本中没有,所以需要事先下载并导入(大神也可以自己写!)。将头文件解压后有两个文件(dht11,h,dht11.c),将这两个文件放在dht11的文件夹里(新建一个),再将文件夹放到IDE的libraries文件夹下。重启IDE。

   接下来就是代码的书写

double Fahrenheit(double celsius) 
{
        return 1.8 * celsius + 32;
}    //摄氏温度度转化为华氏温度

double Kelvin(double celsius)
{
        return celsius + 273.15;
}     //摄氏温度转化为开氏温度

// 露点(点在此温度时,空气饱和并产生露珠)
// 参考: http://wahiduddin.net/calc/density_algorithms.htm 
double dewPoint(double celsius, double humidity)
{
        double A0= 373.15/(273.15 + celsius);
        double SUM = -7.90298 * (A0-1);
        SUM += 5.02808 * log10(A0);
        SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
        SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
        SUM += log10(1013.246);
        double VP = pow(10, SUM-3) * humidity;
        double T = log(VP/0.61078);   // temp var
        return (241.88 * T) / (17.558-T);
}

// 快速计算露点,速度是5倍dewPoint()
// 参考: http://en.wikipedia.org/wiki/Dew_point
double dewPointFast(double celsius, double humidity)
{
        double a = 17.271;
        double b = 237.7;
        double temp = (a * celsius) / (b + celsius) + log(humidity/100);
        double Td = (b * temp) / (a - temp);
        return Td;
}

#include <dht11.h>

dht11 DHT11;

#define DHT11PIN 2
void setup()
{
  Serial.begin(9600);
  Serial.println("DHT11 TEST PROGRAM ");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);
  Serial.println(); 
}

void loop()
{
  Serial.println("\n");

  int chk = DHT11.read(DHT11PIN);

  Serial.print("Read sensor: ");
  switch (chk)
  {
    case DHTLIB_OK: 
                Serial.println("OK"); 
                break;
    case DHTLIB_ERROR_CHECKSUM: 
                Serial.println("Checksum error"); 
                break;
    case DHTLIB_ERROR_TIMEOUT: 
                Serial.println("Time out error"); 
                break;
    default: 
                Serial.println("Unknown error"); 
                break;
  }

  Serial.print("Humidity (%): ");
  Serial.println((float)DHT11.humidity, 2);

  Serial.print("Temperature (oC): ");
  Serial.println((float)DHT11.temperature, 2);

  Serial.print("Temperature (oF): ");
  Serial.println(Fahrenheit(DHT11.temperature), 2);

  Serial.print("Temperature (K): ");
  Serial.println(Kelvin(DHT11.temperature), 2);

  Serial.print("Dew Point (oC): ");
  Serial.println(dewPoint(DHT11.temperature, DHT11.humidity));

  Serial.print("Dew PointFast (oC): ");
  Serial.println(dewPointFast(DHT11.temperature, DHT11.humidity));

  delay(2000);
}

    因为代码中涉及到将摄氏度转化成华氏度和开尔文温度,所以前面写了两个相应的函数。

    最后就是传感器的连接了。不同于LED灯,DHT11有三个针脚,连接的方式也不相同。

    三个针脚中,正极(标有+号的一边,正对是的左端)需要连接在+5v的端口(注意,是arduino板的另一端写有5v的端口).中间的针脚需要接在DIGITAL边的2号端口(写有0~13号端口的那边)。负极接地。




 

   这样就完成了传感器的连接,至于DIGITAL边的端口号,我试过连接其他的端口,但是好像不支持,所以还是直接用2号端口吧。

   接下来,编译,运行,搞定!

猜你喜欢

转载自729660130.iteye.com/blog/2239754