Chapter 21 Hygrothermograph DHT11
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
chk = dht. readDHT11(DHT11_Pin); //read DHT11 and get a return value. Then
determine whether data read is normal according to the return value.
sumCnt++; //counting number of reading times
printf("The sumCnt is : %d \n",sumCnt);
switch(chk){
case DHTLIB_OK: //if the return value is DHTLIB_OK, the data is normal.
printf("DHT11,OK! \n");
b r eak;
case DHTLIB_ERROR_CHECKSUM: //data check has errors
printf("DHTLIB_ERROR_CHECKSUM! \n");
b r eak;
case DHTLIB_ERROR_TIMEOUT: //reading DHT times out
printf("DHTLIB_ERROR_TIMEOUT! \n");
b r eak;
case DHTLIB_INVALID_VALUE: //other errors
printf("DHTLIB_INVALID_VALUE! \n");
b r eak;
}
printf("Humidity is %.2f %%, \t Temperature is %.2f
*C\n\n",dht.humidity,dht.temperature);
delay(1000);
}
r eturn 1;
}
In this project code, we use a custom library file "DHT.hpp". It is located in the same directory with program
files "DHT11.cpp" and "DHT.cpp", and methods for reading DHT sensor are provided in the library file. By
using this library, we can easily read the DHT sensor. First create a DHT class object in the code.
And then in the "while" cycle, use chk = dht.readDHT11 (DHT11_Pin) to read the DHT11, and determine
whether the data read is normal according to the return value "chk". And then use variable sumCnt to record
number of reading times.
wh ile(1){
chk = dht. readDHT11(DHT11_Pin); //read DHT11 and get a return value. Then
determine whether data read is normal according to the return value.
sumCnt++; //count number of times of reading
printf("The sumCnt is : %d \n",sumCnt);
switch(chk){
case DHTLIB_OK: //if the return value is DHTLIB_OK, the data is normal.
printf("DHT11,OK! \n");
b r eak;
case DHTLIB_ERROR_CHECKSUM: //data check has errors
printf("DHTLIB_ERROR_CHECKSUM! \n");
b r eak;
case DHTLIB_ERROR_TIMEOUT: //reading DHT times out