- 1
- #include
- 2
- #include
- 3
- #include
- 4
- #include
- 5 #define
- MAX_TIME 85
- 6 #define
- DHT11PIN 7
- 7 #define
- ATTEMPTS 5
- //retry 5 times when no response
- 8 int
- dht11_val[
- 5
- ]={
- 0
- ,
- 0
- ,
- 0
- ,
- 0
- ,
- 0};
- 9
- 10 int dht11_read_val(){
- 11
- uint8_t lststate=HIGH;
- //last state
- 12
- uint8_t counter=
- 0;
- 13
- uint8_t j=
- 0,i;
- 14 for
- (i=
- 0
- ;i<
- 5
- ;i++
- )
- 15
- dht11_val[i]=
- 0;
- 16
- 17 //host send start signal
- 18
- pinMode(DHT11PIN,OUTPUT);
- //set pin to output
- 19
- digitalWrite(DHT11PIN,LOW);
- //set to low at least 18ms
- 20
- delay(
- 18);
- 21
- digitalWrite(DHT11PIN,HIGH);
- //set to high 20-40us
- 22
- delayMicroseconds(
- 40);
- 23
- 24 //start recieve dht response
- 25
- pinMode(DHT11PIN,INPUT);
- //set pin to input
- 26 for
- (i=
- 0
- ;i
- )
- 27 {
- 28
- counter=
- 0;
- 29 while
- (digitalRead(DHT11PIN)==lststate){
- //read pin state to see if dht responsed. if dht always high for 255 + 1 times, break this while circle
- 30
- counter++
- ;
- 31
- delayMicroseconds(
- 1);
- 32 if
- (counter==
- 255)
- 33 break;
- 34 }
- 35
- lststate=digitalRead(DHT11PIN);
- //read current state and store as last state.
- 36 if
- (counter==
- 255
- )
- //if dht always high for 255 + 1 times, break this for circle
- 37 break;
- 38 // top 3 transistions are ignored, maybe aim to wait for dht finish response signal
- 39 if
- ((i>=
- 4
- )&&(i%
- 2
- ==
- 0)){
- 40
- dht11_val[j/
- 8
- ]<<=
- 1
- ;
- //write 1 bit to 0 by moving left (auto add 0)
- 41 if
- (counter>
- 16
- )
- //long mean 1
- 42
- dht11_val[j/
- 8
- ]|=
- 1
- ;
- //write 1 bit to 1
- 43
- j++
- ;
- 44 }
- 45 }
- 46 // verify checksum and print the verified data
- 47 if
- ((j>=
- 40
- )&&(dht11_val[
- 4
- ]==((dht11_val[
- 0
- ]+dht11_val[
- 1
- ]+dht11_val[
- 2
- ]+dht11_val[
- 3
- ])&
- 0xFF))){
- 48
- printf(
- "RH:%d,TEMP:%d\n"
- ,dht11_val[
- 0
- ],dht11_val[
- 2]);
- 49 return 1;
- 50 }
- 51 else
- 52 return 0;
- 53 }
- 54
- 55 int
- main(
- void){
- 56 int
- attempts=
- ATTEMPTS;
- 57 if
- (wiringPiSetup()==-
- 1)
- 58
- exit(
- 1);
- 59 while
- (attempts){
- //you have 5 times to retry
- 60 int
- success = dht11_read_val();
- //get result including printing out
- 61 if
- (success) {
- //if get result, quit program; if not, retry 5 times then quit
- 62 break;
- 63 }
- 64
- attempts--
- ;
- 65
- delay(
- 2500);
- 66 }
- 67 return 0;
- 68
- }
来源: http://www.bubuko.com/infodetail-2151792.html