//Created by Barbu Vulc!
//This is a Wokwi, realistic simulation of a barrier for a parking area.
//Libraries:
#include <WiFi.h>
#include <ESP32Servo.h>
//Running FreeRTOS on an ESP32 board!
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>

//Create motor object:
Servo motor;
//Attach servomotor to pin 33!
const int servopin = 33;

//Define variables for HC-SR04 ultrasonic distance sensor:
#define echoPin 18   //Attach pin 18 ESP32 to pin Echo of HC-SR04.
#define trigPin 19   //Attach pin 19 ESP32 to pin Trig of HC-SR04.
long duration;       //Variable for the duration of sound wave travel.
int distance;        //Variable for the distance measurement.

void setup() {
  //Initialize serial communication, HC-SR04, WiFi connection & servo:
  Serial.begin(115200);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  Serial.print("Connecting to WiFi");
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");
  motor.attach(servopin);
  //FreeRTOS task:
  xTaskCreate(Task, "task", 1024, NULL, 0, NULL);
}

void Task(void *pvParameters){
  if(WiFi.status() == WL_CONNECTED){
    //Clears the trigPin condition
    digitalWrite(trigPin, LOW);  delay(100);
    //Sets the trigPin HIGH (ACTIVE) for 10 microseconds
    digitalWrite(trigPin, HIGH);  delay(100);
    digitalWrite(trigPin, LOW);
    //Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    //Calculating the distance
    distance = duration * 0.034 / 2; //Speed of sound wave divided by 2 (go and back)
    //Print in serial monitor the deistance between 'a car' & the barrier!
    Serial.println("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");

    /*
     * This is when the barrier is getting off when
     * the distance between 'a car' & sensor is less or equal to 100 cm!
     */
    if(distance < 100){
      //Put the horn at 0 degrees!*
      motor.write(0);  Serial.println("STOP!");
      /* 
       * In real world, in a paid parking area, you have to wait at the barrier...
       * ...for check-in, but the same is aplicable for check-out!
       * Wait 5 seconds for 'car checking'...
       */
      delay(5000); motor.write(90); 
      delay(7000); //Another 7 seconds to let the cars depart!
    }else{
      //Put the horn at 90 degrees!*
      motor.write(90);
    }
  }else{
    //If WiFi connection is lost...
    motor.write(90);
    Serial.println("Unusable for use due to WiFi connection loss!!!");
  }
}

//We won't need 'loop' function here!
void loop() {}

//* = The Servo motor is put partially upside-down!
$abcdeabcde151015202530fghijfghij