DHT11的驱动代码
时间: 2023-08-05 13:05:27 浏览: 117
dht11驱动代码
以下是DHT11的驱动代码,使用C语言编写:
```c
#include <stdio.h>
#include <wiringPi.h>
#define MAX_TIMINGS 85
#define DHT_PIN 7 // 使用wiringPi编号,对应树莓派的GPIO4
int data[5] = { 0, 0, 0, 0, 0 };
void read_dht11_dat()
{
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
pinMode(DHT_PIN, OUTPUT);
digitalWrite(DHT_PIN, LOW);
delay(18);
digitalWrite(DHT_PIN, HIGH);
delayMicroseconds(30);
pinMode(DHT_PIN, INPUT);
for (i = 0; i < MAX_TIMINGS; i++)
{
counter = 0;
while (digitalRead(DHT_PIN) == laststate)
{
counter++;
delayMicroseconds(1);
if (counter == 255)
{
break;
}
}
laststate = digitalRead(DHT_PIN);
if (counter == 255)
break;
if ((i >= 4) && (i % 2 == 0))
{
data[j / 8] <<= 1;
if (counter > 16)
data[j / 8] |= 1;
j++;
}
}
if ((j >= 40) &&
(data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)))
{
printf("Humidity = %d.%d %% Temperature = %d.%d *C\n",
data[0], data[1], data[2], data[3]);
}
else
{
printf("Data not good, skip\n");
}
}
int main(void)
{
printf("DHT11 temperature and humidity sensor\n");
if (wiringPiSetup() == -1)
exit(1);
while (1)
{
read_dht11_dat();
delay(1000); // 每隔1秒读取一次
}
return 0;
}
```
这段代码使用wiringPi库来控制树莓派的GPIO口,读取DHT11传感器的湿度和温度数据。需要注意的是,DHT11传感器的数据线在读取之前需要拉低一段时间,然后再拉高,等待传感器的响应。之后,通过读取数据线的高低电平来解析传感器传回的数据。最后对数据进行校验,判断数据是否正确。
阅读全文