會出現這樣的問題, 主要是因為從 DHT11 讀取到的資料共 5 個位元組, 依序是相對濕度的整數部分、小數部分, 攝氏溫度的整數部分、小數部分, 以及由前面這 4 個位元組相加所得到的校驗值, 在程式庫中就是 bits[0]~bits[4]。不過由於舊版 DHT11 的濕度與溫度精確度都只到整數, 不會有小數, 也就是 bit[1] 和 bit[3] 永遠為 0, 所以程式庫中計算校驗值時就偷懶的只把 bit[0] 和 bit[2] 相加, 如以下所示:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// WRITE TO RIGHT VARS | |
// as bits[1] and bits[3] are allways zero they are omitted in formulas. | |
humidity = bits[0]; | |
temperature = bits[2]; | |
uint8_t sum = bits[0] + bits[2]; | |
if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM; |
當遇到溫度有小數部分時, 上列程式最後一行的校驗值檢查就一定不相等, 所以就無法正確讀取溫濕度了。要解決這個問題很簡單, 只要在計算校驗值時乖乖的把 4 個位元組相加就可以了:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add bits[1] and bits[3] back to formulas to compute correct checksum. | |
humidity = bits[0]; | |
temperature = bits[2]; | |
uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3]; | |
if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM; |
雖然市面上可能還有為數不少的舊版模組, 不過我自己最近買到的就是新版的模組, 還差點因為這個問題以為買到了瑕疵品。大家可以先修改程式庫, 這樣不論新舊版模組都不會有問題。