#include <Arduino_FreeRTOS.h>

// define two tasks for Blink & AnalogRead
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );

#ifdef LED_BUILTIN
uint8_t blink_pin = LED_BUILTIN;
#elif defined(ARDUINO_ELSOMIK)
uint8_t blink_pin = P0_0;
#else
uint8_t blink_pin = 2;
#endif

// the setup function runs once when you press reset or power the board
void setup() {
  
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  
  // Now set up two tasks to run independently.
  xTaskCreate(
    TaskBlink,
    "Blink",  // A name just for humans
    128,      // This stack size can be checked & adjusted by reading the Stack Highwater
    NULL,
    2,        // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
    NULL);

  xTaskCreate(
    TaskAnalogRead,
    "AnalogRead",
    128,      // Stack size
    NULL,
    1,        // Priority
    NULL);

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  Most boards have an on-board LED you can control. You can use it via LED_BUILTIN macro.
  If there is no led on board, you can set different pin to blink_pin variable.
*/

  // initialize blink_pin as an output.
  pinMode(blink_pin, OUTPUT);

  for (;;) // A Task shall never return or exit.
  {
    digitalWrite(blink_pin, HIGH);            // turn the pin on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS );  // wait for one second
    digitalWrite(blink_pin, LOW);             // turn the pin off by making the voltage LOW
    vTaskDelay( 1000 / portTICK_PERIOD_MS );  // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // This is a task.
{
  (void) pvParameters;
  
/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +3V3 and ground.

  This example code is in the public domain.
*/

  for (;;)
  {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    vTaskDelay(250 / portTICK_PERIOD_MS);
  }
}
