Untitled
#include "DHT.h" #include <Wire.h> #include <LiquidCrystal_I2C.h> // Pin definitions #define DHTPIN 2 #define DHTTYPE DHT11 #define RELAY_PIN 3 // Initialize DHT sensor DHT dht(DHTPIN, DHTTYPE); // Initialize I2C LCD with address 0x27 (common address for 16x2 I2C LCDs) LiquidCrystal_I2C lcd(0x27, 16, 2); const int sensorPin = A0; // Analog input pin that the temperature sensor is attached to const int fanPin = 9; // Digital pin that the fan is connected to void setup() { Serial.begin(9600); Serial.println(F("DHTxx test!")); dht.begin(); // Initialize the LCD lcd.init(); lcd.backlight(); lcd.print("Initializing..."); pinMode(RELAY_PIN, OUTPUT); pinMode(fanPin, OUTPUT); // Set the digital pin as output } void loop() { // Wait a few seconds between measurements delay(2000); // Reading temperature and humidity float h = dht.readHumidity(); float t = dht.readTemperature(); // Celsius float f = dht.readTemperature(true); // Fahrenheit // Check if any reads failed and exit early (to try again) if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(F("Failed to read from DHT sensor!")); lcd.clear(); lcd.print("Sensor Error!"); return; } // Compute heat index in Celsius and Fahrenheit float hic = dht.computeHeatIndex(t, h, false); float hif = dht.computeHeatIndex(f, h); // Print to Serial Monitor Serial.print(F("Humidity: ")); Serial.print(h); Serial.print(F("% Temperature: ")); Serial.print(t); Serial.print(F("°C ")); Serial.print(f); Serial.print(F("°F Heat index: ")); Serial.print(hic); Serial.print(F("°C ")); Serial.print(hif); Serial.println(F("°F")); // Display temperature and humidity on the LCD lcd.clear(); lcd.setCursor(0, 0); // Set cursor to first line lcd.print("Temp: "); lcd.print(t); lcd.print(" C"); lcd.setCursor(0, 1); // Set cursor to second line lcd.print("Humidity: "); lcd.print(h); lcd.print(" %"); // Control relay digitalWrite(RELAY_PIN, LOW); delay(2000); digitalWrite(RELAY_PIN, HIGH); delay(2000); // Control fan based on temperature int sensorValue = analogRead(sensorPin); // Read the analog input float voltage = sensorValue * (5.0 / 1023.0); // Convert the analog value to voltage float temperatureC = (voltage - 0.5) * 100.0; // Convert the voltage to temperature in Celsius if (temperatureC > 60.0) { digitalWrite(fanPin, HIGH); // Turn the fan on Serial.println("Fan is ON"); } else { digitalWrite(fanPin, LOW); // Turn the fan off Serial.println("Fan is OFF"); } delay(1000); // Wait for a second before reading again }
Leave a Comment