DHT12.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 "Arduino.h"
  8. #include "Wire.h"
  9. #include "DHT12.h"
  10. DHT12::DHT12(byte scale,byte id)
  11. {
  12. if (id==0 || id>126) _id=0x5c;
  13. else _id=id;
  14. if (scale==0 || scale>3) _scale=CELSIUS;
  15. else _scale=scale;
  16. }
  17. byte DHT12::read()
  18. {
  19. Wire.beginTransmission(_id);
  20. Wire.write(0);
  21. if (Wire.endTransmission()!=0) return 1;
  22. Wire.requestFrom(_id, 5);
  23. for (int i=0;i<5;i++) {
  24. datos[i]=Wire.read();
  25. };
  26. delay(50);
  27. if (Wire.available()!=0) return 2;
  28. if (datos[4]!=(datos[0]+datos[1]+datos[2]+datos[3])) return 3;
  29. return 0;
  30. }
  31. float DHT12::readTemperature(byte scale)
  32. {
  33. float resultado=0;
  34. byte error=read();
  35. if (error!=0) return (float)error/100;
  36. if (scale==0) scale=_scale;
  37. switch(scale) {
  38. case CELSIUS:
  39. resultado=(datos[2]+(float)datos[3]/10);
  40. break;
  41. case FAHRENHEIT:
  42. resultado=((datos[2]+(float)datos[3]/10)*1.8+32);
  43. break;
  44. case KELVIN:
  45. resultado=(datos[2]+(float)datos[3]/10)+273.15;
  46. break;
  47. };
  48. return resultado;
  49. }
  50. float DHT12::readHumidity()
  51. {
  52. float resultado;
  53. byte error=read();
  54. if (error!=0) return (float)error/100;
  55. resultado=(datos[0]+(float)datos[1]/10);
  56. return resultado;
  57. }