#define PIN_ANALOG_IN 1
#define ADC_PRECISION 12
#define ADC_MAX       (double)(1 << ADC_PRECISION)
#define ADC_VOLTAGE   3.3
#define PIN_LED_TOUCH         21
#define TOUCH_PRESS_MIN       132000
#define TOUCH_PRESS_RELEASE   65535
#define PIN_LED_FADE          19
int touchProcessed = 0;
int ledState = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(PIN_LED_TOUCH, OUTPUT);
  ledcAttach(PIN_LED_FADE, 1000, 12);
}

void loop() {
  // put your main code here, to run repeatedly:
  int adcvalue = analogRead(PIN_ANALOG_IN);
  double voltage = adcvalue / ADC_MAX * ADC_VOLTAGE;
  Serial.printf("ADC value : %d\tVoltage: %.2fV\r\n", adcvalue, voltage);
  Serial.printf("Touch value: %d \r\n", touchRead(T14));

  if ( touchRead(T14) > TOUCH_PRESS_MIN  ) {
    if ( touchProcessed == 0 ) {
      touchProcessed = 1;
      if ( ledState == 0 ) {
        digitalWrite(PIN_LED_TOUCH, HIGH);
        ledState = 1;
      } else { 
        digitalWrite(PIN_LED_TOUCH, LOW);
        ledState = 0;
      }
    }
  }

  if ( touchRead(T14) < TOUCH_PRESS_RELEASE ) {
    if ( touchProcessed == 1 ) {
      touchProcessed = 0;
    }
  }
  ledcWrite(PIN_LED_FADE, analogRead(PIN_ANALOG_IN));
  delay(200);
}
