DHT22 -- is it magic or what? 😀

I was taking a brief gander at the Piette-Tech library, but don’t know enough about the DHT22 internals to understand exactly what is happening. I see how _bits is being used to store the 5 bytes (um, I think they should’ve called it _bytes, but anyways …), but how does _bits get its value? I can see something happening in isrCallback(), but the comments say that “isrCallback is only here for backwards compatibility with v0.3 and earlier it is no longer used or needed”.

Can someone, ideally using small words, please explain how _bits gets its values?


I suspect ‘_bits’ is named as such as it holds the ‘bits’ that come from the sensor one at the time.

When acquire() is called, it sends a code to the sensor to start transmitting a response and an interrupt handler (_isrCallBack) is attached to _sigPin. In _isrCallBack() it manages two states: RESPONSE and DATA, look under DATA where it ‘measures’ response times of bits coming from the sensor and based on that adds a bit in _bits[] (_bits[_idx] |= 1;) or does a shift left. This detail is a bit messy in part because the lib is handling (so it seems) a few different sensors with their different response times and in part because bit protocols like these are well… messy :wink:

hope this helps.

Thanks, for your response, joost. Since each element of _bits is actually a byte (there are 5 of them), I’m still lobbying for calling it bytes :sunglasses:. I guess the comment in the code, that "isrCallback is only here for backwards compatibility with v0.3 and earlier it is no longer used or needed” led me to totally ignore that code, making me think that it worked by magic. So, I guess isrCallback() really is being called?

_bits[] or _bytes[] are both not great names to me but hey I didn’t write it.

It is not isrCallBack() you should look at it is _isrCallBack() (ie with leading underscore)

OK, now I really need to go to LensCrafters! Thanks for pointing that out, joost, I am relieved to see that it isn’t magic but code that’s making the library work!

Maybe looking at it differently might help seeing why it’s called _bits.
It’s actually a bunch of bits that get collected one by one whch just happen to be stored in several memory locations that were organised as individual bytes. If we were dealing with a 32bit response of the sensor, we’d put it in a single uint32_t but since there is no 5-byte datatype a uint8_t[5] is the most convenient way to collect the individual bits.

Maybe substituting bits and bytes with grams and kilograms makes it clearer.
If you have a heap of gram-sized entities (e.g. pills) and you count them out one by one they are still a collection of grams (pills) even if you got 10,000 of them, but for convenience you pack them in bags of 1,000 each. So each bag is 1kg but if you are only supposed to take three a day, it’s the gram that counts and not its storage quantity.

1 Like