2121#include <sys/mman.h>
2222#include <sys/types.h>
2323#include <sys/stat.h>
24+ #include <sys/time.h>
2425#include <bcm2835.h>
2526#include <unistd.h>
2627
2728#define MAXTIMINGS 100
2829
30+ //#define DEBUG
31+
2932#define DHT11 11
3033#define DHT22 22
3134#define AM2302 22
@@ -76,30 +79,38 @@ int readDHT(int type, int pin) {
7679
7780 // Set GPIO pin to output
7881 bcm2835_gpio_fsel (pin , BCM2835_GPIO_FSEL_OUTP );
82+
7983 bcm2835_gpio_write (pin , HIGH );
80- usleep (100 );
84+ usleep (500000 ); // 500 ms
8185 bcm2835_gpio_write (pin , LOW );
8286 usleep (20000 );
87+
8388 bcm2835_gpio_fsel (pin , BCM2835_GPIO_FSEL_INPT );
8489
8590 data [0 ] = data [1 ] = data [2 ] = data [3 ] = data [4 ] = 0 ;
91+
92+ // wait for pin to drop?
93+ while (bcm2835_gpio_lev (pin ) == 1 ) {
94+ usleep (1 );
95+ }
96+
8697 // read data!
8798 for (int i = 0 ; i < MAXTIMINGS ; i ++ ) {
8899 counter = 0 ;
89100 while ( bcm2835_gpio_lev (pin ) == laststate ) {
90101 counter ++ ;
91- nanosleep (1 ); // overclocking might change this?
92- if (counter == 100 )
102+ // nanosleep(1); // overclocking might change this?
103+ if (counter == 1000 )
93104 break ;
94105 }
95106 laststate = bcm2835_gpio_lev (pin );
96- if (counter == 100 ) break ;
107+ if (counter == 1000 ) break ;
97108 bits [bitidx ++ ] = counter ;
98109
99110 if ((i > 3 ) && (i %2 == 0 )) {
100111 // shove each bit into the storage bytes
101112 data [j /8 ] <<= 1 ;
102- if (counter > 16 )
113+ if (counter > 200 )
103114 data [j /8 ] |= 1 ;
104115 j ++ ;
105116 }
@@ -109,7 +120,7 @@ int readDHT(int type, int pin) {
109120#ifdef DEBUG
110121 for (int i = 3 ; i < bitidx ; i += 2 ) {
111122 printf ("bit %d: %d\n" , i - 3 , bits [i ]);
112- printf ("bit %d: %d (%d)\n" , i - 2 , bits [i + 1 ], bits [i + 1 ] > 15 );
123+ printf ("bit %d: %d (%d)\n" , i - 2 , bits [i + 1 ], bits [i + 1 ] > 200 );
113124 }
114125#endif
115126
0 commit comments