Guest User

Untitled

a guest
Oct 23rd, 2019
100
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <DHT.h>
  2. #include <LiquidCrystal_I2C.h>
  3.  
  4. #define DHT_PIN 2
  5. #define DHT_TYPE DHT22
  6. #define LCD_WIDTH 16
  7. #define LCD_HEIGHT 2
  8. #define BACKLIGHT_PIN 3
  9. #define IS_FAHRENHEIT false
  10. #define DEGREE_SYMBOL (char)0xdf
  11. // all intervals are in milliseconds
  12. #define UPDATE_INTERVAL 2000
  13. #define BACKLIGHT_ON_INTERVAL 10000
  14. #define FLIP_TO_HI_INTERVAL 5000
  15.  
  16. DHT dht(DHT_PIN, DHT_TYPE);
  17. LiquidCrystal_I2C lcd(0x27, LCD_WIDTH, LCD_HEIGHT);
  18.  
  19. bool backlight_on, read_data, read_failed, flip_to_hi;
  20. unsigned long backlight_time, data_read_time, last_flip_time;
  21.  
  22. void setup() {
  23. pinMode(BACKLIGHT_PIN, INPUT_PULLUP);
  24. lcd.init();
  25. lcd.backlight();
  26. lcd.print("Initializing...");
  27. backlight_on = read_data = true;
  28. read_failed = flip_to_hi = false;
  29. backlight_time = data_read_time = 0;
  30. dht.begin();
  31. }
  32.  
  33. void loop() {
  34. float temperature, humidity, hi;
  35.  
  36. if (read_data) {
  37. temperature = dht.readTemperature(IS_FAHRENHEIT);
  38. humidity = dht.readHumidity();
  39. read_data = false;
  40. data_read_time = millis();
  41.  
  42. // Check if any read fails
  43. if (isnan(temperature) || isnan(humidity)) {
  44. lcd.clear();
  45. lcd.home();
  46. lcd.print("Failed to read");
  47. lcd.setCursor(0, 1);
  48. lcd.print("from DHT sensor");
  49. read_failed = true;
  50. } else if (read_failed)
  51. read_failed = false;
  52.  
  53. if (!read_failed) {
  54. hi = dht.computeHeatIndex(temperature, humidity, IS_FAHRENHEIT);
  55.  
  56. lcd.clear();
  57. if (flip_to_hi) {
  58. lcd.print("Feel : ");
  59. lcd.print(hi);
  60. } else {
  61. lcd.print("Temp. : ");
  62. lcd.print(temperature);
  63. }
  64. lcd.print(" ");
  65. lcd.print(DEGREE_SYMBOL);
  66. if (IS_FAHRENHEIT) lcd.print("F");
  67. else lcd.print("C");
  68. lcd.setCursor(0, 1);
  69. lcd.print("Hum. : ");
  70. lcd.print(humidity);
  71. lcd.print(" %");
  72. }
  73. } else if (millis() - data_read_time >= UPDATE_INTERVAL)
  74. read_data = true;
  75.  
  76. if (backlight_on) {
  77. if (!digitalRead(BACKLIGHT_PIN))
  78. backlight_time = millis();
  79. else if (millis() - backlight_time >= BACKLIGHT_ON_INTERVAL) {
  80. lcd.noBacklight();
  81. backlight_on = false;
  82. }
  83. } else if (!digitalRead(BACKLIGHT_PIN)) {
  84. lcd.backlight();
  85. backlight_time = millis();
  86. backlight_on = true;
  87. }
  88.  
  89. if (millis() - last_flip_time >= FLIP_TO_HI_INTERVAL) {
  90. flip_to_hi = !flip_to_hi;
  91. last_flip_time = millis();
  92. }
  93. }
RAW Paste Data