/*
   Project:       74HC4067_Test
   Description:   Demonstrates use of 4067 to multiplex
                  up to 16 inputs to one analog pin
   Creation date: 7/9/23
   Author:        AnonEngineering

   Tokani Arduino Discord #hardware-help 7/9/23

   License: https://en.wikipedia.org/wiki/Beerware
*/

const int S0_PIN = 11;
const int S1_PIN = 10;
const int S2_PIN =  9;
const int S3_PIN =  8;
const int EN_PIN = 12;
const int MUX_PIN = A0;

void printBits(byte myByte) {
  for (byte mask = 0x08; mask; mask >>= 1) {
    if (mask & myByte)
      Serial.print('1');
    else
      Serial.print('0');
  }
}

void setup() {
  Serial.begin(9600);
  pinMode (S0_PIN, OUTPUT);
  pinMode (S1_PIN, OUTPUT);
  pinMode (S2_PIN, OUTPUT);
  pinMode (S3_PIN, OUTPUT);
  pinMode (EN_PIN, OUTPUT);
  digitalWrite(EN_PIN, LOW);
}

void loop() {
  for (int inputSelect = 0; inputSelect < 16; inputSelect++)  {
    digitalWrite(S3_PIN, inputSelect & 8);
    digitalWrite(S2_PIN, inputSelect & 4);
    digitalWrite(S1_PIN, inputSelect & 2);
    digitalWrite(S0_PIN, inputSelect & 1);
    delay(10); // needed on Wokwi at least, setup time?
    Serial.print("Input select: ");
    Serial.print(inputSelect);
    Serial.print(" \t");
    Serial.print("Binary: 0b");
    //Serial.print(inputSelect, BIN);
    printBits(inputSelect);
    Serial.print("\t\t");
    Serial.print("Reading: ");
    Serial.println(analogRead(MUX_PIN));
    delay(1000);
  }
}