DHTtester.ino 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Example testing sketch for various DHT humidity/temperature sensors
  2. // Written by ladyada, public domain
  3. // REQUIRES the following Arduino libraries:
  4. // - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
  5. // - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
  6. #include "DHT.h"
  7. #define DHTPIN 2 // Digital pin connected to the DHT sensor
  8. // Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
  9. // Pin 15 can work but DHT must be disconnected during program upload.
  10. // Uncomment whatever type you're using!
  11. //#define DHTTYPE DHT11 // DHT 11
  12. #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
  13. //#define DHTTYPE DHT21 // DHT 21 (AM2301)
  14. // Connect pin 1 (on the left) of the sensor to +5V
  15. // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
  16. // to 3.3V instead of 5V!
  17. // Connect pin 2 of the sensor to whatever your DHTPIN is
  18. // Connect pin 4 (on the right) of the sensor to GROUND
  19. // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
  20. // Initialize DHT sensor.
  21. // Note that older versions of this library took an optional third parameter to
  22. // tweak the timings for faster processors. This parameter is no longer needed
  23. // as the current DHT reading algorithm adjusts itself to work on faster procs.
  24. DHT dht(DHTPIN, DHTTYPE);
  25. void setup() {
  26. Serial.begin(9600);
  27. Serial.println(F("DHTxx test!"));
  28. dht.begin();
  29. }
  30. void loop() {
  31. // Wait a few seconds between measurements.
  32. delay(2000);
  33. // Reading temperature or humidity takes about 250 milliseconds!
  34. // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  35. float h = dht.readHumidity();
  36. // Read temperature as Celsius (the default)
  37. float t = dht.readTemperature();
  38. // Read temperature as Fahrenheit (isFahrenheit = true)
  39. float f = dht.readTemperature(true);
  40. // Check if any reads failed and exit early (to try again).
  41. if (isnan(h) || isnan(t) || isnan(f)) {
  42. Serial.println(F("Failed to read from DHT sensor!"));
  43. return;
  44. }
  45. // Compute heat index in Fahrenheit (the default)
  46. float hif = dht.computeHeatIndex(f, h);
  47. // Compute heat index in Celsius (isFahreheit = false)
  48. float hic = dht.computeHeatIndex(t, h, false);
  49. Serial.print(F("Humidity: "));
  50. Serial.print(h);
  51. Serial.print(F("% Temperature: "));
  52. Serial.print(t);
  53. Serial.print(F("°C "));
  54. Serial.print(f);
  55. Serial.print(F("°F Heat index: "));
  56. Serial.print(hic);
  57. Serial.print(F("°C "));
  58. Serial.print(hif);
  59. Serial.println(F("°F"));
  60. }