#include <DHT.h>
#include <LiquidCrystal.h>
#define pinDatos 18 // DHT22 data pin
#define pinPulsador 4 // On button
#define pinPulsador2 5 // Off button
#define pinLed 2 // On LED
#define pinLed2 15 // Off LED
#define pinLed3 23 // New LED
#define trigPin 34 // HC-SR04 Trigger pin
#define echoPin 35 // HC-SR04 Echo pin
LiquidCrystal lcd(22, 21, 13, 12, 14, 27); // LCD Pins
DHT sensorTH(pinDatos, DHT22); // DHT Sensor
void setup() {
Serial.begin(115200);
lcd.begin(16, 2); // Initialize the LCD
sensorTH.begin(); // Initialize DHT sensor
pinMode(pinPulsador, INPUT);
pinMode(pinPulsador2, INPUT);
pinMode(pinLed, OUTPUT);
pinMode(pinLed2, OUTPUT);
pinMode(pinLed3, OUTPUT); // New LED
// Initialize the HC-SR04
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Read the state of the buttons
int pulsadorState = digitalRead(pinPulsador);
int pulsador2State = digitalRead(pinPulsador2);
lcd.setCursor(0, 0); // Set cursor position for LCD
if (pulsadorState == HIGH) {
digitalWrite(pinLed, HIGH); // Turn on the On LED
digitalWrite(pinLed2, LOW); // Turn off the Off LED
float humedad = sensorTH.readHumidity();
float temperatura = sensorTH.readTemperature();
lcd.print("Temp: ");
lcd.print(temperatura);
lcd.print("C");
lcd.setCursor(0, 1);
lcd.print("Humedad: ");
lcd.print(humedad);
lcd.print("%");
if (temperatura <= 24.0) {
digitalWrite(pinLed3, HIGH); // Turn on the new LED
} else {
digitalWrite(pinLed3, LOW); // Turn off the new LED
}
// Measure distance with the HC-SR04
float distancia = medirDistancia();
Serial.print("Distance = ");
Serial.print(distancia);
Serial.println(" cm");
} else if (pulsador2State == HIGH) {
Serial.print("System Off <3 ");
digitalWrite(pinLed2, HIGH); // Turn on the Off LED
digitalWrite(pinLed, LOW); // Turn off the On LED
digitalWrite(pinLed3, LOW); // Turn off the new LED
lcd.clear(); // Clear the LCD screen
} else {
// If neither button is pressed, turn off both LEDs
digitalWrite(pinLed, LOW);
digitalWrite(pinLed2, LOW);
digitalWrite(pinLed3, LOW); // Turn off the new LED
lcd.clear(); // Clear the LCD screen
}
}
float medirDistancia() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long tiempoEcho = pulseIn(echoPin, HIGH);
float distancia = tiempoEcho / 58.2;
return distancia;
}