DHT.cpp 10 KB

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