简介:DHT11是一款有已校准数字信号输出的温湿度传感器。 该传感器内部包括一个电阻式感湿元件和一个NTC测温元件。在使用上其精度湿度±5%RH, 温度±2℃,量程湿度5~95%RH, 温度-20~+60℃
原文转自
http://www.raspi.cc/index.php?c=read&id=251&page=1
那么今天我们在写一个C语言的实例教程。对于完全0基础的小白按照教程一步步来也能轻松实现!
二:安装 WiringPi
这里使用了 WiringPi 库,(如果已经安装过可以跳过这一步)依次输入下面五条命令进行安装
sudo apt-get update
sudo apt-get install git-core
git clone https://github.com/WiringPi/WiringPi
cd WiringPi
sudo ./build
四:代码程序
新建dht11.c文件,保存下面代码程序,ctrl+x保存按Y (不会新建的朋友可以输入sudo nano dht11.c来新建文件)
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uint8;
typedef unsigned int uint16;
typedef unsigned long uint32;
#define HIGH_TIME 32
int pinNumber = 7;
uint32 databuf;
uint8 readSensorData(void)
{
uint8 crc;
uint8 i;
pinMode(pinNumber, OUTPUT); // set mode to output
digitalWrite(pinNumber, 0); // output a high level
delay(25);
digitalWrite(pinNumber, 1); // output a low level
pinMode(pinNumber, INPUT); // set mode to input
pullUpDnControl(pinNumber, PUD_UP);
delayMicroseconds(27);
if (digitalRead(pinNumber) == 0) //SENSOR ANS
{
while (!digitalRead(pinNumber))
; //wait to high
for (i = 0; i < 32; i++)
{
while (digitalRead(pinNumber))
; //data clock start
while (!digitalRead(pinNumber))
; //data start
delayMicroseconds(HIGH_TIME);
databuf *= 2;
if (digitalRead(pinNumber) == 1) //1
{
databuf++;
}
}
for (i = 0; i < 8; i++)
{
while (digitalRead(pinNumber))
; //data clock start
while (!digitalRead(pinNumber))
; //data start
delayMicroseconds(HIGH_TIME);
crc *= 2;
if (digitalRead(pinNumber) == 1) //1
{
crc++;
}
}
return 1;
}
else
{
return 0;
}
}
int main(void)
{
printf("PIN:%d\n", pinNumber);
if (-1 == wiringPiSetup()) {
printf("Setup wiringPi failed!");
return 1;
}
pinMode(pinNumber, OUTPUT); // set mode to output
digitalWrite(pinNumber, 1); // output a high level
printf("Starting...\n");
while (1)
{
pinMode(pinNumber, OUTPUT); // set mode to output
digitalWrite(pinNumber, 1); // output a high level
delay(3000);
if (readSensorData())
{
printf("Sensor data read ok!\n");
printf("RH:%d.%d\n", (databuf >> 24) & 0xff, (databuf >> 16) & 0xff);
printf("TMP:%d.%d\n", (databuf >> 8) & 0xff, databuf & 0xff);
databuf = 0;
}
else
{
printf("Sensor dosent ans!\n");
databuf = 0;
}
}
return 0;
}
五:编译程序并运行
gcc -Wall -o dht11 dht11.c -lwiringPi
忽略编译过程中的警告。运行之后将出现温湿度读数。
在执行下面命令可获取温度数据
sudo ./dht11