#include <ESP32Servo.h>  // Library untuk kontrol ESC menggunakan PWM

const int hallSensorPin1 = 18;
const int hallSensorPin2 = 22;
const int hallSensorPin3 = 23;
const int escPin = 19; // Pin untuk ESC

float rpm;
float rps;
volatile unsigned long counter = 0;
float kecepatan;
unsigned long lalu = millis();
unsigned long sekarang;

Servo esc; // Objek Servo untuk ESC
int escSignal = 1504.9; // Nilai default untuk ESC

// Fungsi untuk menghitung lebar pulsa dari kecepatan (km/jam) menggunakan regresi polinomial
float regresiPolinomial(float x) {
  return  (0.2383 * x * x * x) - (5.2815 * x * x) + (39.703 * x) + 1506.7;
}

void IRAM_ATTR hallInterrupt() { counter++; }
void IRAM_ATTR hallInterrupt2() { counter++; }
void IRAM_ATTR hallInterrupt3() { counter++; }

void setup() {
  Serial.begin(9600);

  // Konfigurasi pin sensor sebagai input1
  pinMode(hallSensorPin1, INPUT_PULLUP);
  pinMode(hallSensorPin2, INPUT_PULLUP);
  pinMode(hallSensorPin3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(hallSensorPin1), hallInterrupt, RISING);
  attachInterrupt(digitalPinToInterrupt(hallSensorPin2), hallInterrupt2, RISING);
  attachInterrupt(digitalPinToInterrupt(hallSensorPin3), hallInterrupt3, RISING);

  // Konfigurasi ESC menggunakan PWM
  esc.attach(escPin, 1000, 2000); // ESC menggunakan sinyal PWM 1ms-2ms (1000-2000µs)
  Serial.println("Masukkan nilai kecepatan (0-20 KM/Jam) via Serial Monitor:");
}

void loop() {
  // Membaca input dari Serial Monitor
  if (Serial.available() > 0) {
    int inputValue = Serial.parseInt();
    Serial.flush();  // Membersihkan buffer input Serial
    
    // Validasi input agar tetap dalam rentang 0 - 20 KM/Jam
    if (inputValue >= 0 && inputValue <= 20) {
      escSignal = (float)regresiPolinomial(inputValue); // Ubah km/jam ke PWM
      Serial.print("ESC Signal diatur ke: ");
      Serial.println(escSignal);
    } else {
      Serial.println("Masukkan nilai 0 - 20 KM/Jam.");
    }
  }

  // Mengatur ESC berdasarkan nilai input
  esc.writeMicroseconds(escSignal);

  sekarang = millis();
  if (sekarang - lalu >= 1000) {
    rps = (float)counter / 21;
    rpm = (float)counter * 60 / 21;
   
    kecepatan = (float)counter / 21 * 3600 / 100000 * PI * 5 / 3;

    // Menampilkan hasil ke Serial Monitor
    Serial.print("Kecepatan : ");
    Serial.print(kecepatan);
    Serial.print(" km/jam | RPM : ");
    Serial.print(rpm, 1);
    Serial.print(" | RPS : ");
    Serial.print(rps, 1);
    Serial.print(" | ESC Signal: ");
    Serial.println(escSignal);

    counter = 0;
    lalu = sekarang;
  }

  delay(1); // Stabilisasi loop
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK