#include <Arduino.h> //library used for ledc

const int analogInPin = 32; //Assigns the GPIO to read the analog input from (must be a pin labelled as ADC)
const int in1 = 23; //GPIO to control motor direction
const int in2 = 22; //GPIO to control motor direction
const int enA = 21; //GPIO pin that we will output our pulse width modulated signal on

const int freq = 30000;    //frequency of the output signal (the inverse of the period)(how many times per second)
const int resolution = 8;  //sets the number of values the signal can be (2^8 or 256 in this case)
const int pwmChannel = 2;  // the selected pwm channel to use

//selected pwm can have conflicts with ESP32Servo which is assigned automatically (try changing this value if it's not working)

int stickPos = 0;  //stroes value of analog input from 0 to 4096
float speed = 0;  //stores led brightness from 0 to 255

void setup() {
  Serial.begin(115200);   // starts the seroal monitor (the console we can write to)

  //set pins for digital output
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  //creates a controlable pulse width modulated signal on the channel that we defined
  ledcSetup(pwmChannel, freq, resolution);

  //attaches the pin we defined to the pwm signal we just set up (multiple pins can be connected to one signal)
  ledcAttachPin(enA, pwmChannel);  
}

void loop() {
  //reads the volatege on the defined analog pin from 0V to 3.3V and maps it to a value between 0 and 4096
  stickPos = analogRead(analogInPin);
  
  speed = map(stickPos,0,4096,-255,255);

  //Prints the variable values to the serial terminal
  Serial.print("\nInput:  ");
  Serial.print(stickPos);

  Serial.print("  Motor Speed:  ");
  Serial.print(speed);

  if (speed >= 0) 
  {
        // set pins for forward direction
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
  } 
  else 
  {
        // set pins for backwards direction
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
        speed = -speed;
  }
  //sets the duty cycle of the PWM signal (0 is 0% high, 100% low and 255 is 100% high, 0% low)
  ledcWrite(pwmChannel, speed);
  
  delay(20);
}

float mapf(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}