//Created by Barbu Vulc!
//Based on this project: https://wokwi.com/projects/374931089542986753
//Using an ESP32 board at its full potential!
//Libraries:
#include <WiFi.h>
#include <ESP32Servo.h>
#include <LiquidCrystal_I2C.h>
//Create servo & LCD objects:
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo servomotor;
//Variables:
const int servopin = 18;

//WiFi connection...
void setup() {
  //Initiate serial communication, LCD & Servo motor:
  Serial.begin(115200);
  servomotor.attach(servopin);
  lcd.init();  lcd.backlight();

  //Verify if WiFi connection is successfully done:
  Serial.print("Connected to WiFi!");
  //Connect board NodeMCU-32S to a WiFi network(Name, password, channel):
  WiFi.begin("Wokwi-GUEST", "", 6);
  //Board is not connecting to WiFi instantaneously, so we have to wait some moments:
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println("Connected!");
  delay(100);
}

//The project...
void loop() {
  //Random value between 0 & 180:
  int rnd = random(0, 180);
  //Move servo horn either by connection (which means move by potentiometer's given value)...
  if (WiFi.status() == WL_CONNECTED) {
    servomotor.write(rnd);
    lcd.setCursor(0, 0);  lcd.print(rnd);  
    lcd.setCursor(4, 0);  lcd.print("degrees"); 
    delay(1000);
    lcd.clear();
  }else{
    //In case of connection loss...
    servomotor.write(0);
    lcd.setCursor(0, 0);  lcd.print("  Error!  ");
    delay(100);
  }
}