//Source: https://robojax.com/learn/arduino/?vid=robojax_ESP32_Bluetooth_LED_blink
//BluetoothSerial library:
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

//Create BT object:
BluetoothSerial SerialBT;
int received;      //Received value will be stored in this variable.
char receivedChar; //Received value will be stored as CHAR in this variable.

const char turnON = '1';
const char turnOFF = '0';
const int LEDpin = LED_BUILTIN; 

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32_Wokwi"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");
  Serial.println("To turn ON the LED send: 1");//print on serial monitor
  Serial.println("To turn OFF the LED send: 0"); //print on serial monitor
  pinMode(LEDpin, OUTPUT);
}

void loop() {
  receivedChar = (char)SerialBT.read();

  if (Serial.available()) {
    SerialBT.write(Serial.read());

    if (receivedChar == turnON) {
      SerialBT.println("LED ON:");
      Serial.println("LED ON:");    //write on serial monitor
      digitalWrite(LEDpin, HIGH);   //turn the LED ON
    } 
    if (receivedChar == turnOFF) {
      SerialBT.println("LED OFF:");
      Serial.println("LED OFF:");   //write on serial monitor
      digitalWrite(LEDpin, LOW);    //turn the LED off
    }
  } 

  delay(100);
  /*
  Serial.println(" BT stopping "); 
  SerialBT.flush(); SerialBT.disconnect(); 
  SerialBT.end(); Serial.println(" BT stopped ");
  */
}