I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.
Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).
My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is > 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.
I hope I've been clear enough and that someone can point me the right way!
EDIT:
Here is the schematic
(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)
And my code:
#define MUX A0
#define S0 A2
#define S1 A3
void setup() {
Serial.begin(9600);
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
selectMux(1);
}
void loop() {
//selectMux(0);
//Serial.println(analogRead(MUX));
//selectMux(1);
Serial.println(analogRead(MUX));
}
void selectMux(byte port) {
// pinMode(MUX, mode);
int r0 = bitRead(port, 0);
int r1 = bitRead(port, 1);
digitalWrite(S0, r0);
digitalWrite(S1, r1);
analogRead(MUX);
}
the analogRead(MUX)
in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading.
With this code only the results already fluctuate:
Output:
76
41
77
76
76
75
36
75
74
76
77
106
76
76
76
76
but it goes crazy when the input is higher, close to 5V:
Output:
948
780
340
948
948
635
437
949
948
499
551
949
950
396
684
950
If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.
I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.