#include <LiquidCrystal_I2C.h>

QueueHandle_t queue_1;
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 column and 2 rows

#define TRIG_PIN 18 // ESP32 pin GIOP23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 5 // ESP32 pin GIOP22 connected to Ultrasonic Sensor's ECHO pin
float duration_us, distance_cm;
const int led =4;
const int pir =19;

void setup() {
  lcd.init(); // initialize the lcd
  lcd.backlight();
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(led,OUTPUT);
  pinMode(pir,INPUT);

  xTaskCreatePinnedToCore(task1,"task1",4000,NULL,1,NULL,1);
  xTaskCreatePinnedToCore(task2,"task2",4000,NULL,1,NULL,1);
  xTaskCreatePinnedToCore(task3,"task3",4000,NULL,1,NULL,1);
  //vTaskStartScheduler();
}

void task1(void*pt)
{
  
  while(1){
    long Timestart = millis();
    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIG_PIN, LOW);                      // display the above for two seconds
    duration_us = pulseIn(ECHO_PIN, HIGH);
    // calculate the distance
    distance_cm = 0.017 * duration_us;
    long task1_time = millis()-Timestart;
    Serial.print("execute_time1 =");
    Serial.println(task1_time);
    delay(500);
  }
}

void task2(void*pt)
{
  
  while(1){
    long Timestart2 = millis();
    const int IP=digitalRead(pir);
    
    if(IP==1)
    {
      digitalWrite(led,HIGH);
      //Serial.println("ada org");  
    }
    else
    {
      digitalWrite(led,LOW);
      //Serial.println("xada org"); 
    }
    long task2_time = millis()-Timestart2;
    Serial.print("Execute_time2 =");
    Serial.println(task2_time);
    delay(500);
  }
}

void task3(void*pt)
{
  pinMode(2, INPUT_PULLUP);

  while(1){
      long Timestart3 = millis();
      lcd.clear();              // clear display
      lcd.setCursor(0, 0);      
      lcd.print("distance=");
      lcd.setCursor(10, 0);      
      lcd.print(distance_cm);
      long task3_time = millis()-Timestart3;
      Serial.print("execute_time3 =");
      Serial.println(task3_time);
      delay(1000);     
  }
}
void loop() { 
}