#include <Arduino.h>
#include <Wire.h>

// Define the CD74HC4067 pins
const int s0Pin = 2;
const int s1Pin = 3;
const int s2Pin = 4;
const int s3Pin = 5;
const int analogInPin = 0; // Connect this to the common pin (Y0) of CD74HC4067
const int ldrMapMin = 0;   // Minimum mapping value for LDRs
const int ldrMapMax = 1023; // Maximum mapping value for LDRs
const unsigned long interval = 500; // Delay between readings (1 second)

unsigned long previousMillis = 0;

void setup() {
  // Initialize the CD74HC4067 pins
  pinMode(s0Pin, OUTPUT);
  pinMode(s1Pin, OUTPUT);
  pinMode(s2Pin, OUTPUT);
  pinMode(s3Pin, OUTPUT);

  // Start the serial communication for displaying values
  Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    for (int channel = 0; channel < 16; channel++) {
      // Set the MUX to the current channel
      selectMuxChannel(channel);

      // Read the analog value from the selected channel
      int sensorValue = analogRead(analogInPin);

      // Map the values for channels 4-7 to channels 0-3
      int mappedValue;
      if (channel >= 4 && channel <= 7) {
        // Use the potentiometer values to map the LDR readings
        int potValue = analogRead(channel - 4); // Read the corresponding potentiometer value
        mappedValue = map(sensorValue, 0, 1023, ldrMapMin, potValue);
      } else {
        mappedValue = sensorValue;
      }

      // Differentiate between LDRs and potentiometers
      if (channel >= 0 && channel <= 3) {
        Serial.print("LDR");
      } else if (channel >= 4 && channel <= 7) {
        Serial.print("Potentio");
      } else {
        continue; // Ignore other channels
      }

      Serial.print(channel % 4); // Display channel number (0-3) for LDRs and (0-3) for Potentiometers
      Serial.print(" : ");
      Serial.print(mappedValue);

      if (channel == 7) {
        Serial.println(); // Print a new line after processing channels 0-3 and 4-7
      } else {
        Serial.print(" : ");
      }
    }
  }
}

void selectMuxChannel(int channel) {
  // Set the MUX channel by setting the appropriate S0-S3 pins
  digitalWrite(s0Pin, channel & 0x01);
  digitalWrite(s1Pin, (channel >> 1) & 0x01);
  digitalWrite(s2Pin, (channel >> 2) & 0x01);
  digitalWrite(s3Pin, (channel >> 3) & 0x01);
}