/*
   EX4_MultiTasking_FreeRTOS_DHT22_OLED
   การแบ่ง task ทำงาน โดยควบคุมหลอดไฟ LED กระพริบคนละจังหวะ
   อ่านค่าอุณหภูมิและความชื้นจากเซนเซอร์ DHT22 มาแสดงผลในคอนโซล
   และแสดงค่าในจอ OLED
*/

///-------------------ตั้งค่าที่นี่------------------///

#define LED1 32
#define LED2 33
#define LED3 25 //build-in LED on board
#define DHTTYPE dht22
#define DHTPIN 15

///------------------------------------------///
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LiquidCrystal_I2C lcd(0x27,16,2); //  LCD address to 0x27 for a 16 chars and 2 line display

#include "DHTesp.h"                //โหลดไลบารี่ dht22
const int DHT_PIN = 15;
DHTesp dhtSensor;

///------------------------------------------///
void Task1(void *p) {
  pinMode(LED1, OUTPUT);
  while (1) {
    digitalWrite(LED1, !digitalRead(LED1));
    vTaskDelay(100 / portTICK_PERIOD_MS);
  }
}

///------------------------------------------///
void Task2(void *p) {
  pinMode(LED2, OUTPUT);
  while (1) {
    digitalWrite(LED2, !digitalRead(LED2));
    vTaskDelay(500 / portTICK_PERIOD_MS);
  }
}

///------------------------------------------///
void Task3(void *p) {
  pinMode(LED3, OUTPUT);
  while (1) {
    digitalWrite(LED3, !digitalRead(LED3));
    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
}

///------------------------------------------///
void Task4(void *p) {
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  LiquidCrystal_I2C lcd(0x27, 16, 2);
  lcd.init(); lcd.backlight();
  while (1) {
    TempAndHumidity  data = dhtSensor.getTempAndHumidity();
    Serial.println("Temp: " + String(data.temperature, 2) + "C");
    Serial.println("Humidity: " + String(data.humidity, 1) + "%");
    Serial.println("---");

    // lcd.init();
    // lcd.backlight();
    lcd.setCursor(0, 0);
    lcd.print("T:" + String(data.temperature, 2) + "C");

    lcd.setCursor(9, 0);
    lcd.println("H:" + String(data.humidity, 1) + "%" );

    vTaskDelay(2000 / portTICK_PERIOD_MS);
  }
}

void setup() {
  Serial.begin(115200);
  xTaskCreate(&Task1, "Task1", 1024, NULL, 10, NULL);
  xTaskCreate(&Task2, "Task2", 1024, NULL, 10, NULL);
  xTaskCreate(&Task3, "Task3", 1024, NULL, 10, NULL);
  xTaskCreatePinnedToCore(&Task4, "Task4", 10000, NULL, 10, NULL, 1);
}

void loop() {
}