树莓派dht11代码C语言代码
时间: 2023-07-03 22:31:54 浏览: 114
DHT11的C程序
以下是树莓派上使用wiringPi库读取DHT11传感器数据的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#define MAX_TIME 85
#define DHT11PIN 7
int dht11_val[5]={0,0,0,0,0};
void dht11_read_val()
{
unsigned char lststate=HIGH;
unsigned char counter=0;
unsigned char j=0,i;
for(i=0;i<5;i++)
dht11_val[i]=0;
pinMode(DHT11PIN,OUTPUT);
digitalWrite(DHT11PIN,LOW);
delay(18);
digitalWrite(DHT11PIN,HIGH);
delayMicroseconds(40);
pinMode(DHT11PIN,INPUT);
for(i=0;i<MAX_TIME;i++)
{
counter=0;
while(digitalRead(DHT11PIN)==lststate)
{
counter++;
delayMicroseconds(1);
if(counter==255)
break;
}
lststate=digitalRead(DHT11PIN);
if(counter==255)
break;
if((i>=4)&&(i%2==0))
{
dht11_val[j/8]<<=1;
if(counter>16)
dht11_val[j/8]|=1;
j++;
}
}
if((j>=40)&&(dht11_val[4]==((dht11_val[0]+dht11_val[1]+dht11_val[2]+dht11_val[3])& 0xff)))
printf("Humidity = %d.%d %% Temperature = %d.%d *C\n",dht11_val[0],dht11_val[1],dht11_val[2],dht11_val[3]);
else
printf("Invalid Data!!\n");
}
int main(void)
{
if(wiringPiSetup()==-1)
exit(1);
while(1)
{
dht11_read_val();
delay(5000);
}
return 0;
}
```
该代码通过wiringPi库中的GPIO控制函数,读取DHT11传感器的输出,实现了温湿度的测量。在主函数中,通过循环执行dht11_read_val()函数,实现了每隔五秒钟测量一次温湿度的功能。
阅读全文