DHT12.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. if (id == 0 || id > 126)
  10. _id = 0x5c;
  11. else
  12. _id = id;
  13. if (scale == 0 || scale > 3)
  14. _scale = CELSIUS;
  15. else
  16. _scale = scale;
  17. }
  18. uint8_t DHT12::read() {
  19. Wire.beginTransmission(_id);
  20. Wire.write(0);
  21. if (Wire.endTransmission() != 0) return 1;
  22. Wire.requestFrom(_id, (uint8_t)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(uint8_t scale) {
  32. float resultado = 0;
  33. uint8_t error = read();
  34. if (error != 0) return (float)error / 100;
  35. resultado = datos[2] + (float)(datos[3] & 0x7f) / 10;
  36. if (datos[3] & 0x80) {
  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. float resultado;
  54. uint8_t error = read();
  55. if (error != 0) return (float)error / 100;
  56. resultado = (datos[0] + (float)datos[1] / 10);
  57. return resultado;
  58. }