#include <CD74HC4067.h>
// Define the pins for the CD74HC4067
const int s0 = 16;
const int s1 = 17;
const int s2 = 26;
const int s3 = 27;
const int sig = 34; // Analog input pin for the multiplexer output
// Define the channels for the KY-040 rotary encoder
const int clkChannel = 0; // Channel 0 for CLK
const int dtChannel = 1;  // Channel 1 for DT
const int swChannel = 2;  // Channel 2 for SW
// Variables to store the state of the rotary encoder
int lastClkState = -1;
int lastEncoderValue = -1;
int lastButtonValue  = -1;
CD74HC4067 mux1(s0, s1, s2, s3);
void IRAM_ATTR test() {
  Serial.println("BTN!");
  delay(100); // For Simulation
}
const int pwr = 39;
void setup() {
  Serial.begin(115200);
  pinMode(pwr, INPUT);
  // pinMode(sig, OUTPUT);
  pinMode(sig, INPUT_PULLUP);
  while (!Serial);
  Serial.println("setup complete");
  attachInterrupt(pwr, test, RISING);
}
void loop() {
  // get clock value through mux
  mux1.channel(clkChannel);
  delay(10); // For Simulation
  int newClk = digitalRead(sig);
  if (newClk != lastClkState){ 
    lastClkState = newClk;
    Serial.print("Rotary clock value: ");
    Serial.println(newClk);
  // }
  // get rotary value through mux
  mux1.channel(swChannel);
  delay(10); // For Simulation
  int encoderValue = digitalRead(sig);
  // if (encoderValue != lastEncoderValue){ 
    // lastEncoderValue = encoderValue;
    Serial.print("Rotary encoder value: ");
    Serial.println(encoderValue);
  // }
  // get button value through mux
  mux1.channel(swChannel);
  delay(10); // For Simulation
  int buttonValue = digitalRead(sig);
  // if (buttonValue != lastButtonValue){ 
    // lastButtonValue = buttonValue;
    Serial.print("Rotary btn value: ");
    Serial.println(buttonValue);
  // }
  }
}