//Created by Barbu Vulc!
/*
  This is a sketch done with the goal of... 
  simulating an industrial production line!
*/
//Libraries:
#include <Arduino_FreeRTOS.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

//Declare LEDs & buzzer variables:
const int green_led = 10;
const int red_led = 9;
const int yellow_led = 7;
const int buzzer = 12;

void setup() {
  Serial.begin(9600);
  //LCD initialization!
  lcd.init(); lcd.backlight();

  //LEDs' initialization!
  pinMode(green_led, OUTPUT);  pinMode(red_led, OUTPUT);
  pinMode(yellow_led, OUTPUT);
  //Buzzer initialization!
  pinMode(buzzer, OUTPUT);

  //Tasks' creation!
  xTaskCreate(Task1, "Proces no. 1!", 128, NULL, 1, NULL);
  xTaskCreate(Task2, "Stop process!", 128, NULL, 2, NULL);
  xTaskCreate(Task3, "Process no. 2!", 128, NULL, 3, NULL);
  xTaskCreate(Neutral_Task, "Fault!", 128, NULL, 0, NULL);
}

//Task for green LED:
static void Task1(void* pvParameters) {
  while (1) {
    digitalWrite(green_led, HIGH);
    digitalWrite(red_led, LOW);
    digitalWrite(yellow_led, LOW);
    tone(buzzer, 200, 200);
    Serial.println(F("Process no. 1!"));

    lcd.setCursor(0, 0);
    lcd.print("Start process!");
    delay(500);  lcd.clear();

    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
}

//Task for red LED:
static void Task2(void* pvParameters) {
  while (1) {
    digitalWrite(green_led, LOW);
    digitalWrite(red_led, HIGH);
    digitalWrite(yellow_led, LOW);
    tone(buzzer, 400, 400);
    Serial.println(F("Stop process!"));

    lcd.setCursor(0, 0);
    lcd.print("Stop process!");
    lcd.clear();

    vTaskDelay(500 / portTICK_PERIOD_MS);
  }
}

//Task for the same green LED: 
static void Task3(void* pvParameters) {
  while (1) {
    digitalWrite(green_led, HIGH);
    digitalWrite(red_led, LOW);
    digitalWrite(yellow_led, LOW);
    tone(buzzer, 200, 200);
    Serial.println(F("Process no. 2!"));

    lcd.setCursor(0, 0);
    lcd.print("Start process!");
    lcd.clear();

    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
}

//Task for yellow LED:
static void Neutral_Task(void* pvParameters) {
  while (1) {
    digitalWrite(green_led, LOW);
    digitalWrite(red_led, LOW);
    digitalWrite(yellow_led, HIGH);
    tone(buzzer, 1400, 100);
    delay(100);
    tone(buzzer, 1400, 100);
    Serial.println(F("Fault!"));

    lcd.setCursor(0, 0);
    lcd.print("ERROR!!!");
    lcd.setCursor(0, 1);
    lcd.print("Fault occured!");
    lcd.clear();

    vTaskDelay(400 / portTICK_PERIOD_MS);
  }
}

void loop() {}