/*
  ESP32 Analog MUX Read
  Read potentiometer voltage at different MUX inputs
 Hopefully to run on a Cheap Yellow Display - hence odd pin numers

 Based on sketch Written by Ahmad Shamshiri at 20:55
  on Sunday Sep 01, 2019 in Ajax, Ontario, Canada

  Watch Video instruction for this sketch:
  https://youtu.be/UXKu2Xtwj7c

  Messed about with By Neil Fenwick 30/06/2024 in Dorset, UK
    it's a bit scrappy, but does seem to work
*/
#define E 27
#define S0 5
#define S1 18
#define S2 19
#define S3 23

const int potPin = 35;// Analog pin

int x = 2;  // delay for mux to settle

int potValue;// do not change
float voltage = 0; // do not change

void printStuff(int) {
   voltage = (3.3 / 4095.0) * potValue;
  Serial.print("potValue:");
  Serial.print(potValue);

  Serial.print(" Voltage:");
  Serial.print(voltage);
  Serial.println("V");
  delay(1000); // delay in between reads for testing
}

void setup() {
pinMode(E, OUTPUT);
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(potPin, INPUT);

  // initialize serial communication at 115200 bits per second:
  Serial.begin(115200);
}


void loop() {
  digitalWrite(E, HIGH);  // Disable chip before changing channel.
  delay(x);
  digitalWrite(S0, 0);  //
  digitalWrite(S1, 0);  //  sets the bits to switch the mux
  digitalWrite(S2, 0);  //
  digitalWrite(S3, 0);  //
  delay(x);
  digitalWrite(E, LOW);   // Reenable chip
  // read the input on analog pin potPin:
  potValue = analogRead(potPin);
  delay(x);
  Serial.println("pot 1");
  printStuff(potValue);

 digitalWrite(E, HIGH);  // Disable chip before changing channel.
   delay(x);
  digitalWrite(S0, 1);
  digitalWrite(S1, 0);
  digitalWrite(S2, 0);
  digitalWrite(S3, 0);
  delay(x);
  digitalWrite(E, LOW);
  // read the input on analog pin potPin:
  potValue = analogRead(potPin);
  delay(x);
  Serial.println("pot 2");
  printStuff(potValue);

 digitalWrite(E, HIGH);  // Disable chip before changing channel.
  delay(x);
  digitalWrite(S0, 0);
  digitalWrite(S1, 1);
  digitalWrite(S2, 0);
  digitalWrite(S3, 0);
  delay(x);
  digitalWrite(E, LOW);
  // read the input on analog pin potPin:
  potValue = analogRead(potPin);
  delay(x);
  Serial.println("pot 3");
  printStuff(potValue);

 digitalWrite(E, HIGH);  // Disable chip before changing channel.
   delay(x);
  digitalWrite(S0, 1);
  digitalWrite(S1, 1);
  digitalWrite(S2, 0);
  digitalWrite(S3, 0);
  delay(x);
  digitalWrite(E, LOW);
  // read the input on analog pin potPin:
  potValue = analogRead(potPin);
  delay(x);
  Serial.println("pot 4");
  printStuff(potValue);

}