用C语言编写一个dht11的C文件
时间: 2023-05-29 10:01:35 浏览: 79
由于缺少具体的硬件和环境,我提供一个基础的dht11的C文件,代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#define MAX_TIMINGS 85
#define DHT_PIN 7 // 可根据具体情况修改GPIO编号
int data[5] = {0, 0, 0, 0, 0};
void read_dht11_data() {
int i,j = 0;
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);
int laststate = HIGH;
for(i = 0; i < MAX_TIMINGS; i++) {
int count = 0;
while(digitalRead(DHT_PIN) == laststate) {
count++;
delayMicroseconds(1);
if(count == 255) {
break;
}
}
laststate = digitalRead(DHT_PIN);
if(count == 255) break;
if((i >= 4) && (i % 2 == 0)) {
data[j / 8] <<= 1;
if(count >= 50) {
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_data();
delay(2000);
}
return 0;
}
```
使用前需要确认wiringPi库已安装,可通过以下命令安装:
```
sudo apt-get updatesudo apt-get install wiringPi
```
然后通过命令行编译运行即可,命令如下:
```
gcc dht11.c -lwiringPi -o dht11sudo ./dht11
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)