前引

Arduino中已经有关于DHT11的库,但是为了理解模块的运行原理,而写了这个代码,代码中的不足之处还请多多指正。

关于DHT11的原理,在之前的文章中已经提到过,就不再赘述。

代码部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#define DHT11 15
void setup() {
Serial.begin(115200);

}

void loop() {
dht();
delay(2000);
}

void dht(){
double hum,tem;
pinMode(DHT11,OUTPUT);
digitalWrite(DHT11,HIGH);
delay(2);
digitalWrite(DHT11,LOW);
delay(25);
digitalWrite(DHT11,HIGH);
delayMicroseconds(30);
pinMode(DHT11,INPUT);
if(!digitalRead(DHT11)){
Serial.println("ok");
while(!digitalRead(DHT11));
delayMicroseconds(10);
while(digitalRead(DHT11));
int humInt=getData();
int humDec=getData();
int temInt=getData();
int temDec=getData();
int Check=getData();
if((humInt+humDec+temInt+temDec)==Check){
if(humDec<10){
hum=humInt+humDec/10.0;
}else if(humDec<100){
hum=humInt+humDec/100.0;
}
if(temDec<10){
tem=temInt+temDec/10.0;
}else if(temDec<100){
tem=temInt+temDec/100.0;
}
Serial.print("温度:");
Serial.print(tem);
Serial.println();
Serial.print("湿度:");
Serial.print(hum);
Serial.println();
}
}
else{
Serial.println("error");
}

}

int getData(){
byte Data;
byte temp;
for(int i=0 ;i<8;i++){
while(!digitalRead(DHT11));
delayMicroseconds(35);

if(digitalRead(DHT11)){
temp=0x01;
}else{
temp=0x00;
}
Data<<=1;
Data|=temp;
while(digitalRead(DHT11));
delayMicroseconds(10);
}
return Data;
}