DHT12.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. DHT12.cpp - Library for DHT12 sensor.
  3. v0.0.1 Beta
  4. Created by Bobadas, July 30,2016.
  5. Released into the public domain.
  6. */
  7. #include "DHT12.h"
  8. DHT12::DHT12(uint8_t scale,uint8_t id)
  9. {
  10. if (id==0 || id>126) _id=0x5c;
  11. else _id=id;
  12. if (scale==0 || scale>3) _scale=CELSIUS;
  13. else _scale=scale;
  14. }
  15. uint8_t DHT12::read()
  16. {
  17. Wire.beginTransmission(_id);
  18. Wire.write(0);
  19. if (Wire.endTransmission()!=0) return 1;
  20. Wire.requestFrom(_id, (uint8_t)5);
  21. for (int i=0;i<5;i++) {
  22. datos[i]=Wire.read();
  23. };
  24. delay(50);
  25. if (Wire.available()!=0) return 2;
  26. if (datos[4]!=(datos[0]+datos[1]+datos[2]+datos[3])) return 3;
  27. return 0;
  28. }
  29. float DHT12::readTemperature(uint8_t scale)
  30. {
  31. float resultado=0;
  32. uint8_t error=read();
  33. if (error!=0) return (float)error/100;
  34. resultado=datos[2]+(float)(datos[3]&0x7f)/10;
  35. if(datos[3]&0x80)
  36. {
  37. resultado = -resultado;
  38. }
  39. if (scale==0) scale=_scale;
  40. switch(scale) {
  41. case CELSIUS:
  42. break;
  43. case FAHRENHEIT:
  44. resultado=resultado*1.8+32;
  45. break;
  46. case KELVIN:
  47. resultado=resultado+273.15;
  48. break;
  49. };
  50. return resultado;
  51. }
  52. float DHT12::readHumidity()
  53. {
  54. float resultado;
  55. uint8_t error=read();
  56. if (error!=0) return (float)error/100;
  57. resultado=(datos[0]+(float)datos[1]/10);
  58. return resultado;
  59. }