Dht11 sensor

Guys i have a project to do for university.i need to use Dht11 sensor to control temperature and humidity in a box with fertilized eggs.i dont understand the part of the source file which reads each bit.totally 40 bits.it is used an array with 5 cells.this is the code :

for (int i=0; i<40; i++)
55 {
56 loopCnt = 10000;
57 while(digitalRead(pin) == LOW)
58 if (loopCnt-- == 0) return -2;
59
60 unsigned long t = micros();
61
62 loopCnt = 10000;
63 while(digitalRead(pin) == HIGH)
64 if (loopCnt-- == 0) return -2;
65
66 if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
67 if (cnt == 0) // next byte?
68 {
69 cnt = 7; // restart at MSB
70 idx++; // next byte!
71 }
72 else cnt–;
73 }

can someone please explain the line 66? what is going on there?how the microcontroller knows what value to give to each bit?i dont see somewhere the use of data protocol of dht11.i mean i dont see it inside the source file.how arduino knows about it?
bit 0 is ~54?s low and ~24?s high .
bit 1 is ~54?s low and ~70?s high

That almost all inside the line you made bold. If the time of the last pulse was more than 40µs, treat it as a 1, else it's a 0. As the byte array was initialized to 0, you don't have to change anything in the zero case, else move the 1 bit to it's place in the current byte and use a boolean OR operation to set it.

thank you very much for reply pylon.it was really helpful. i understood what u mean.but why the time number is 40?

but why the time number is 40?

The exact middle between 24 and 70 would be 47. I guess the library writer has chosen a value a bit lower because that resulted in more reliable results during his tests. Probably anything between 35 and 55 works in most cases.

thanks again.you helped me much :slight_smile:

The library writer choose this because 40 is the "harmonic" average of 24 and 70 rounded to a multiple of 4 micros.

40/24 = 1.6666
70/40 = 1.75

so in terms of relative error margin it is the middle :slight_smile: