#include <Wire.h>
#include <LiquidCrystal.h>
#include <RTClib.h>
#include <PIDController.h>
#include <dht.h>
#define DHT22_PIN 15
// Objects
PIDController pid; // Create an instance of the PID controller class, called "pid"
dht DHT;
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
// Pins
int outputPin = 3; // The pin the digital output PWM is connected to
int sensorPin = A0; // The pin the analog sensor is connected to
int fanPin = 6; // The pin the digital output is connected to control the "fan" (LED)
// Variables
double setpointValue = 20.0; // Variable to store the setpoint value
void setup () {
Serial.begin(9600); // Some methods require the Serial.begin() method to be called first
pinMode(outputPin, OUTPUT);
pinMode(sensorPin, INPUT);
pinMode(fanPin, OUTPUT);
pid.begin(); // initialize the PID instance
pid.tune(1, 1, 1); // Tune the PID, arguments: kP, kI, kD
pid.limit(0, 255); // Limit the PID output between 0 and 255, this is important to get rid of integral windup!
// Set the initial setpoint value
pid.setpoint(setpointValue);
// Initialize LCD
lcd.begin(16, 2);
}
void loop () {
// Leer el valor del potenciómetro y actualizar setpointValue
int potValue = analogRead(sensorPin);
setpointValue = map(potValue, 0, 1023, 0, 100); // Mapear de 0 a 5V a 0 a 100ºC
int sensorValue = analogRead(sensorPin); // Read the value from the sensor
// Leer la temperatura actual del sensor DHT
int chk = DHT.read22(DHT22_PIN);
float temperature = DHT.temperature;
// Verificar si la lectura del sensor es válida
if (chk == DHTLIB_OK) {
// Calcular el error
float error = setpointValue - temperature;
// Imprimir el valor del error
Serial.print("Error: ");
Serial.println(error);
// Verificar si la temperatura es mayor a 25°C para activar el "ventilador" (LED)
if (temperature > 25) {
digitalWrite(fanPin, HIGH); // Encender el "ventilador"
} else {
digitalWrite(fanPin, LOW); // Apagar el "ventilador"
}
int output = pid.compute(sensorValue); // Let the PID compute the value, returns the optimal output
analogWrite(outputPin, output); // Write the output to the output pin
// Mostrar valores en la pantalla LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Setpoint: ");
lcd.print(setpointValue);
lcd.print(" C");
} else {
Serial.println("Error al leer el sensor DHT.");
}
delay(1000); // Delay for 1 second
}