DHT.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /* DHT library
  2. MIT license
  3. written by Adafruit Industries
  4. */
  5. #include <math.h>
  6. #include "DHT.h"
  7. //#define NAN 0
  8. #ifdef DEBUG
  9. #define DEBUG_PRINT(...) Serial.println(__VA_ARGS__)
  10. #else
  11. #define DEBUG_PRINT(...)
  12. #endif
  13. DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
  14. _pin = pin;
  15. _type = type;
  16. _count = count;
  17. firstreading = true;
  18. }
  19. void DHT::begin(void) {
  20. if (_type == DHT10) {
  21. if (DHT10Init()) {
  22. SERIALPRINT.println("Error : Failed to init DHT 11\n");
  23. while (1);
  24. }
  25. } else {
  26. // set up the pins!
  27. pinMode(_pin, INPUT);
  28. digitalWrite(_pin, HIGH);
  29. _lastreadtime = 0;
  30. }
  31. }
  32. /** Common interface to get temp&humi value.support all DHT device.
  33. @return 0 for calibrated failed,1 for succeed.
  34. **/
  35. int DHT::readTempAndHumidity(float* data) {
  36. uint32_t target_val[2] = {0};
  37. uint32_t cnt;
  38. if (_type == DHT10) {
  39. while (DHT10ReadStatus() == 0) {
  40. DHT10Init();
  41. delay(30);
  42. cnt++;
  43. if (cnt > 3) {
  44. return -1;
  45. }
  46. }
  47. //wait for data ready。
  48. while (readTargetData(target_val)) {
  49. cnt++;
  50. delay(50);
  51. if (cnt > 5) {
  52. return -1;
  53. }
  54. }
  55. data[0] = target_val[0] * 100.0 / 1024 / 1024;
  56. data[1] = target_val[1] * 200.0 / 1024 / 1024 - 50;
  57. } else {
  58. data[0] = readHumidity();
  59. data[1] = readTemperature();
  60. if (isnan(data[0]) || isnan(data[1])) {
  61. return -1;
  62. }
  63. }
  64. return 0;
  65. }
  66. //boolean S == Scale. True == Farenheit; False == Celcius
  67. float DHT::readTemperature(bool S) {
  68. float f;
  69. if (read()) {
  70. switch (_type) {
  71. case DHT11:
  72. f = data[2];
  73. if(data[3]%128<10){
  74. f += data[3]%128/10.0f;
  75. }else if(data[3]%128<100){
  76. f += data[3]%128/100.0f;
  77. }else{
  78. f += data[3]%128/1000.0f;
  79. }
  80. if(data[3]>=128){ // The left-most digit indicate the negative sign.
  81. f = -f;
  82. }
  83. if (S) {
  84. f = convertCtoF(f);
  85. }
  86. return f;
  87. case DHT22:
  88. case DHT21:
  89. f = data[2] & 0x7F;
  90. f *= 256;
  91. f += data[3];
  92. f /= 10;
  93. if (data[2] & 0x80) {
  94. f *= -1;
  95. }
  96. if (S) {
  97. f = convertCtoF(f);
  98. }
  99. return f;
  100. }
  101. }
  102. DEBUG_PRINT("Read fail");
  103. return NAN;
  104. }
  105. float DHT::convertCtoF(float c) {
  106. return c * 9 / 5 + 32;
  107. }
  108. float DHT::readHumidity(void) {
  109. float f;
  110. if (read()) {
  111. switch (_type) {
  112. case DHT11:
  113. f = data[0];
  114. return f;
  115. case DHT22:
  116. case DHT21:
  117. f = data[0];
  118. f *= 256;
  119. f += data[1];
  120. f /= 10;
  121. return f;
  122. }
  123. }
  124. DEBUG_PRINT("Read fail");
  125. return NAN;
  126. }
  127. boolean DHT::read(void) {
  128. uint8_t laststate = HIGH;
  129. uint8_t counter = 0;
  130. uint8_t j = 0, i;
  131. unsigned long currenttime;
  132. // pull the pin high and wait 250 milliseconds
  133. digitalWrite(_pin, HIGH);
  134. delay(250);
  135. currenttime = millis();
  136. if (currenttime < _lastreadtime) {
  137. // ie there was a rollover
  138. _lastreadtime = 0;
  139. }
  140. if (!firstreading && ((currenttime - _lastreadtime) < 2000)) {
  141. return true; // return last correct measurement
  142. //delay(2000 - (currenttime - _lastreadtime));
  143. }
  144. firstreading = false;
  145. /*
  146. DEBUG_PRINT("Currtime: "); DEBUG_PRINT(currenttime);
  147. DEBUG_PRINT(" Lasttime: "); DEBUG_PRINT(_lastreadtime);
  148. */
  149. _lastreadtime = millis();
  150. data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  151. // now pull it low for ~20 milliseconds
  152. pinMode(_pin, OUTPUT);
  153. digitalWrite(_pin, LOW);
  154. delay(20);
  155. //cli();
  156. digitalWrite(_pin, HIGH);
  157. delayMicroseconds(40);
  158. pinMode(_pin, INPUT);
  159. // read in timings
  160. for (i = 0; i < MAXTIMINGS; i++) {
  161. counter = 0;
  162. while (digitalRead(_pin) == laststate) {
  163. counter++;
  164. delayMicroseconds(1);
  165. if (counter == 255) {
  166. break;
  167. }
  168. }
  169. laststate = digitalRead(_pin);
  170. if (counter == 255) {
  171. break;
  172. }
  173. // ignore first 3 transitions
  174. if ((i >= 4) && (i % 2 == 0)) {
  175. // shove each bit into the storage bytes
  176. data[j / 8] <<= 1;
  177. if (counter > _count) {
  178. data[j / 8] |= 1;
  179. }
  180. j++;
  181. }
  182. }
  183. //sei();
  184. /*
  185. DEBUG_PRINTln(j, DEC);
  186. DEBUG_PRINT(data[0], HEX); DEBUG_PRINT(", ");
  187. DEBUG_PRINT(data[1], HEX); DEBUG_PRINT(", ");
  188. DEBUG_PRINT(data[2], HEX); DEBUG_PRINT(", ");
  189. DEBUG_PRINT(data[3], HEX); DEBUG_PRINT(", ");
  190. DEBUG_PRINT(data[4], HEX); DEBUG_PRINT(" =? ");
  191. DEBUG_PRINTln(data[0] + data[1] + data[2] + data[3], HEX);
  192. */
  193. // check we read 40 bits and that the checksum matches
  194. if ((j >= 40) &&
  195. (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF))) {
  196. return true;
  197. }
  198. return false;
  199. }
  200. /*****************************************************************************/
  201. /*****************************************************************************/
  202. /** Reset sensor.
  203. @return 0 for calibrated failed,1 for succeed.
  204. **/
  205. int DHT::DHT10Reset(void) {
  206. if (_type == DHT10) {
  207. return i2cWriteByte(RESET_REG_ADDR);
  208. } else {
  209. return 0;
  210. SERIALPRINT.println("This function only support for DHT10");
  211. }
  212. }
  213. /** Read status register.check the calibration flag - bit[3]: 1- calibrated ok ,0 - Not calibrated.
  214. @return 0 for calibrated failed,1 for succeed.
  215. **/
  216. int DHT::DHT10ReadStatus(void) {
  217. int ret = 0;
  218. uint8_t statu = 0;
  219. if (_type == DHT10) {
  220. ret = i2cReadByte(statu);
  221. if (ret) {
  222. SERIALPRINT.println("Failed to read byte\n");
  223. }
  224. if ((statu & 0x8) == 0x8) {
  225. return 1;
  226. } else {
  227. return 0;
  228. }
  229. } else {
  230. SERIALPRINT.println("This function only support for DHT10");
  231. return 0;
  232. }
  233. }
  234. /** Init sensor,send 0x08,0x00 to register 0xe1.
  235. @ return : 0 if success, non-zero if failed.
  236. **/
  237. int DHT::setSystemCfg(void) {
  238. uint8_t cfg_param[] = {0xe1, 0x08, 0x00};
  239. if (_type == DHT10) {
  240. return i2cWriteBytes(cfg_param, sizeof(cfg_param));
  241. } else {
  242. SERIALPRINT.println("This function only support for DHT10");
  243. return 0;
  244. }
  245. }
  246. /** Read temp & humi result buf from sensor.
  247. total 6 bytes,the first byte for status register,other 5 bytes for temp & humidity data.
  248. @ return : 0 if success, non-zero if failed.
  249. **/
  250. int DHT::readTargetData(uint32_t* data) {
  251. uint8_t statu = 0;
  252. uint8_t bytes[6] = {0};
  253. uint8_t cfg_params[] = {0xac, 0x33, 0x00};
  254. int ret = 0;
  255. if (_type == DHT10) {
  256. if (i2cWriteBytes(cfg_params, sizeof(cfg_params))) {
  257. return -1;
  258. }
  259. delay(75);
  260. // check device busy flag, bit[7]:1 for busy, 0 for idle.
  261. while (statu & 0x80 == 0x80) {
  262. SERIALPRINT.println("Device busy!");
  263. delay(200);
  264. if (i2cReadByte(statu)) {
  265. return -1;
  266. }
  267. }
  268. if (i2cReadBytes(bytes, sizeof(bytes))) {
  269. return -1;
  270. }
  271. data[HUMIDITY_INDEX] = (data[HUMIDITY_INDEX] | bytes[1]) << 8;
  272. data[HUMIDITY_INDEX] = (data[HUMIDITY_INDEX] | bytes[2]) << 8;
  273. data[HUMIDITY_INDEX] = (data[HUMIDITY_INDEX] | bytes[3]);
  274. data[HUMIDITY_INDEX] = data[HUMIDITY_INDEX] >> 4;
  275. data[TEMPRATURE_INDEX] = (data[TEMPRATURE_INDEX] | bytes[3]) << 8;
  276. data[TEMPRATURE_INDEX] = (data[TEMPRATURE_INDEX] | bytes[4]) << 8;
  277. data[TEMPRATURE_INDEX] = (data[TEMPRATURE_INDEX] | bytes[5]);
  278. data[TEMPRATURE_INDEX] &= 0xfffff;
  279. return 0;
  280. } else {
  281. SERIALPRINT.println("This function only support for DHT10");
  282. return 0;
  283. }
  284. }
  285. /** DHT10 Init function.
  286. Reset sensor and wait for calibration complete.
  287. @ return : 0 if success, non-zero if failed.
  288. **/
  289. int DHT::DHT10Init(void) {
  290. int ret = 0;
  291. int cnt = 0;
  292. if (_type == DHT10) {
  293. delay(500);
  294. DHT10Reset();
  295. delay(300);
  296. ret = setSystemCfg();
  297. if (ret) {
  298. SERIALPRINT.println("Failed to set system conf reg \n");
  299. }
  300. //SERIALPRINT.println("Set system cfg OK!");
  301. delay(500);
  302. while (DHT10ReadStatus() == 0) {
  303. SERIALPRINT.println("get status error!");
  304. DHT10Reset();
  305. delay(500);
  306. if (setSystemCfg()) {
  307. SERIALPRINT.println("Failed to set system conf reg \n");
  308. }
  309. delay(500);
  310. cnt++;
  311. if (cnt > 5) {
  312. return -1;
  313. }
  314. }
  315. return 0;
  316. } else {
  317. SERIALPRINT.println("This function only support for DHT10");
  318. return 0;
  319. }
  320. }
  321. /*****************************************************************************/
  322. /*****************************************************************************/
  323. int DHT::i2cReadByte(uint8_t& byte) {
  324. int cnt = 0;
  325. Wire.requestFrom(DEFAULT_IIC_ADDR, 1);
  326. while (1 != Wire.available()) {
  327. cnt++;
  328. if (cnt >= 10) {
  329. return -1;
  330. }
  331. delay(1);
  332. }
  333. byte = Wire.read();
  334. return 0;
  335. }
  336. int DHT::i2cReadBytes(uint8_t* bytes, uint32_t len) {
  337. int cnt = 0;
  338. Wire.requestFrom(DEFAULT_IIC_ADDR, len);
  339. while (len != Wire.available()) {
  340. cnt++;
  341. if (cnt >= 10) {
  342. return -1;
  343. }
  344. delay(1);
  345. }
  346. for (int i = 0; i < len; i++) {
  347. bytes[i] = Wire.read();
  348. }
  349. return 0;
  350. }
  351. int DHT::i2cWriteBytes(uint8_t* bytes, uint32_t len) {
  352. Wire.beginTransmission(DEFAULT_IIC_ADDR);
  353. for (int i = 0; i < len; i++) {
  354. Wire.write(bytes[i]);
  355. }
  356. return Wire.endTransmission();
  357. }
  358. int DHT::i2cWriteByte(uint8_t byte) {
  359. Wire.beginTransmission(DEFAULT_IIC_ADDR);
  360. Wire.write(byte);
  361. return Wire.endTransmission();
  362. }