#include "DHTesp.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <LiquidCrystal_I2C.h>
#define LED_PIN 4 // Define el pin donde está conectado el LED
#define LDR_PIN 12
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define DHT_PIN 15
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
TaskHandle_t xHandlePrintTemperature;
TaskHandle_t xHandleCheckLight;
int systemStatus = 1;
DHTesp dhtSensor;
int getThreshold(void){
// The potentiometer has a resolution from 0 to 4095 so this will be interpolated
// to temperatures from 18º to 30º
// So, 30-18 = 12. So the potentiometer will control the temperature in 12 slots
// meaning, the valued read from the potentiometer has to be divided by 341 aproximately
int value = analogRead(36);
return value/341+18;
}
int getTemp(void){
TempAndHumidity data = dhtSensor.getTempAndHumidity();
return data.temperature;
}
void vTaskPeriodicPrintTemperature(void* pvParam)
{
const TickType_t xDelay = 250 / portTICK_PERIOD_MS;
for(;;) {
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
// Clear the buffer
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(1,0);
display.clearDisplay();
char buffer[80]; // Asegúrate de que el buffer es suficientemente grande para la cadena completa.
snprintf(buffer, sizeof(buffer), "Temp actual: %d\nThreshold: %d", getTemp(), getThreshold());
display.println(buffer);
display.display();
vTaskDelay(xDelay);
}
vTaskDelete(NULL);
}
void vTaskPeriodicCheckLight(void* pvParam)
{
const TickType_t xDelay = 5000 / portTICK_PERIOD_MS;
for(;;){
if (digitalRead(LDR_PIN) == LOW) {
if(systemStatus == 0){
Serial.println("Light! System on\n");
systemStatus = 1;
digitalWrite(LED_PIN, HIGH); // set the LED to the opposite state
vTaskResume(xHandlePrintTemperature);
}
} else {
if(systemStatus ==1){
systemStatus = 0;
Serial.println("Dark! System off\n");
vTaskSuspend(xHandlePrintTemperature);
digitalWrite(LED_PIN, LOW); // set the LED to the opposite state
}
}
vTaskDelay(xDelay);
}
vTaskDelete(NULL);
}
void app_main(){
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(LDR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
xTaskCreate(vTaskPeriodicPrintTemperature, "Task 3", 1500, NULL, 1, &xHandlePrintTemperature);
xTaskCreate(vTaskPeriodicCheckLight, "Task 4", 1500, NULL, 1, &xHandleCheckLight);
digitalWrite(LED_PIN, HIGH);
}
void setup() {
app_main();
}
void loop() {
}