I am trying to use an UNO R4 wifi with a CD74HC4067 analog multiplexer to read the values of a bunch inputs on one pin. Some of the inputs are potentiometers and some switches, and the mux connects them all to one pin, so my thought was to connect the mux to an analog pin and do digitalReads for the switches and analogReads for the pots. The 4 select lines of the multiplexer are connected to digital pins, and the common I/O pin to A5. There is a 10k external pullup on A5, and the pots/switches go through the mux from A5 to ground. My code is below:
//inputs
#define INPUT_MUX_PIN A5
#define S0 9
#define S1 10
#define S2 11
#define S3 12
uint16_t channels[16];
void setupMux(){ //setup the pins for the multiplexer
pinMode(INPUT_MUX_PIN, INPUT);
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
}
void selectChannel(uint8_t channel){ //write mux selector pins to connect a channel
if(channel < 16){
digitalWrite(S0, (channel & 0b0001));
digitalWrite(S1, (channel & 0b0010));
digitalWrite(S2, (channel & 0b0100));
digitalWrite(S3, (channel & 0b1000));
}
}
uint16_t readInput(uint8_t channel = 0, uint8_t digital_read = 0){
uint16_t read_val = 1;
if(channel < 16){
selectChannel(channel);
delayMicroseconds(1); //allow for switching time, very conservative estimate
if(digital_read){
read_val = digitalRead(INPUT_MUX_PIN);
}
else{
read_val = (uint16_t)analogRead(INPUT_MUX_PIN);
}
channels[channel] = read_val;
}
return read_val;
}
void setup(){
//setup serial
Serial.begin(9600);
//setup ADC and mux
setupMux();
}
void loop(){
//read and print the pin values
delay(500);
Serial.println();
Serial.println(readInput(15));
Serial.println(readInput(15,1));
Serial.println(readInput(14));
Serial.println(readInput(14,1));
}
When I run this code, the analogReads return correct values, but the digitalReads always return 0. If I delete the analogRead calls and only do digitalReads, it returns correct values. Any idea what is wrong? I know I could just always do analogReads and shift the values to get a digital 1/0, but I want to understand what is not working.