#include <ESP32Servo.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"

#define LEDPin GPIO_NUM_19
#define ButtonPin GPIO_NUM_15

const int servoPin = 18;

xTaskHandle TaskHandle_1;
xTaskHandle TaskHandle_2;
xTaskHandle TaskHandle_3;

uint8_t led_value = 0;

Servo servo;

void setup() {
  gpio_set_direction(LEDPin,GPIO_MODE_OUTPUT);
  //gpio_set_direction(ButtonPin,GPIO_MODE_INPUT);
  pinMode(ButtonPin, INPUT_PULLUP);
  servo.attach(servoPin, 544, 2400);
}

void turnLED(void *pvParameter)
{
  while(1)
  {
    gpio_set_level(LEDPin,led_value);
    led_value = !led_value;
    vTaskDelay(300 / portTICK_PERIOD_MS);
  }
}

int pos = 0;

void moveServo(void *pvParameter)
{
  while(1)
  {
    for (pos = 0; pos <= 180; pos += 1) {
    servo.write(pos);
    delay(100);
   }
  }
}

void pressButton(void *pvParameter)
{
  while(1)
  {
      int le_botao=digitalRead(ButtonPin);
       vTaskDelay(100 / portTICK_PERIOD_MS);
    if  (le_botao==LOW)
    {
      vTaskSuspend(TaskHandle_3);
    }
    
    else 
    {
      vTaskResume (TaskHandle_3);
    }
  }
}


void loop() {
  xTaskCreate(&pressButton,"pressButton", 1024, NULL, 5, &TaskHandle_1);
  xTaskCreate(&turnLED,"turnLED", 1024, NULL, 2, &TaskHandle_2);
  xTaskCreate(&moveServo,"moveServo", 1024, NULL, 2, &TaskHandle_3);
}