// Incluimos librería
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#define DHTPIN 2 //
#define DHTTYPE DHT11 // Dependiendo del tipo de sensor
LiquidCrystal_I2C lcd(0x27,16,2);
DHT dht(DHTPIN, DHTTYPE); // Inicializamos el sensor DHT11
int pinRelay1 = 7;
int Sensor = A0;
int h; //Stores humidity value
int t; //Stores temperature value
int setpoint = 45; //
float kp = 0.1; //
float ki = 1; //
float kd = 1; //
double integral; //
double prevvils_error; //
double derivative; //
double porportonal; //
double output; //
int pwm; // Variable de lectura del pwm
float sensed_output; // lectura del sensor DHT11
double error; // Error
float time_seconds = 0;// Para el contador por segundos
void setup() {
Serial.begin(9600);
Serial.println("Temperature and Humidity Sensor Test"); // Inicializamos comunicación serie
dht.begin(); // Comenzamos el sensor DHT
lcd.init(); //initialize the lcd
lcd.backlight(); //open the backlight
Serial.println("Micro Projects TH");
pinMode(pinRelay1, OUTPUT);
}
void loop() {
delay(3000); // Retraso de lectura debido a las limitaciones del sensor
sensed_output = dht.readTemperature(); // Leemos la temperatura en grados centígrados (por defecto)
time_seconds = (millis()) / 1000;
control_PID(); // Funcion del control P
{
h = dht.readHumidity();
t = dht.readTemperature();
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %, Temp: ");
Serial.print(t);
Serial.println(" ° Celsius");
// set the cursor to (0,0):
{
Sensor = analogRead(A0);
Serial.print("Sensor : "); Serial.println(Sensor);
if (Sensor < 1) {
digitalWrite(pinRelay1, LOW);
}
else if (Sensor >= 1) {
digitalWrite(pinRelay1, HIGH);
}
delay(1000);
}
// print from 0 to 9:
lcd.setCursor(0, 0);
lcd.println(" Simple Circuits");
lcd.setCursor(0, 1);
lcd.print(" T:");
lcd.print(t);
lcd.print("C");
lcd.setCursor(11, 1);
lcd.print("H:");
lcd.print(h);
lcd.print("%");
delay(1000);
}
}
void control_PID() {
error = setpoint - sensed_output;
porportonal = error;
integral = integral + (error * (50 / 1000)) ;
derivative = (error - prevvils_error ) / 50 / 1000;
output = kp * porportonal + ki * integral + kd * derivative;
prevvils_error = error;
if (pwm >= 255) pwm = 255; //Limitador del control
else if (pwm <= 30) pwm = 30 ;
analogWrite(5, pwm );
}
void impirmir_valores_DATA() { //Imprime valores en el display LCD 1602
Serial.print(time_seconds);
Serial.print(",");
Serial.print(sensed_output);
Serial.print(",");
Serial.print(error);
Serial.print(porportonal);
Serial.print(integral);
Serial.print(output);
Serial.print(prevvils_error);
Serial.print(",");
Serial.println(pwm);
}