Strange CD4051 behaviour

Hi. I use CD4051 to read analog data from multiple sensors. The problem is that data comes with huge error. To check whether it's sensors error or multiplexer I've decided to connect all CD4051 data inputs to the Vdd. In this case I get something like: 53, 793, 766, 810, 782, 812, 804, 822 (data from each data input). I expect all values to be equal. I've tried CD4051 from different shops. What is the problem? Thanks.

#define ANALOG_PIN A0
#define OUT_A 2
#define OUT_B 3
#define OUT_C 4
 
void setup() {
  pinMode(OUT_A, OUTPUT);
  pinMode(OUT_B, OUTPUT);
  pinMode(OUT_C, OUTPUT);
  Serial.begin(9600);
}

void loop() {   
   for (int i = 0b000; i <= 0b111; i++) {
     digitalWrite(OUT_A, bitRead(i, 0));
     digitalWrite(OUT_B, bitRead(i, 1));
     digitalWrite(OUT_C, bitRead(i, 2));

     Serial.print(i);
     Serial.print(": ");
     Serial.print(analogRead(ANALOG_PIN));
     Serial.print(" | ");
   }
   Serial.println();
   delay(500);
}
for (int i = 0b000; i <= 0b111; i++)

Why, this works equally as well:-

for (int i = 0; i <= 7; i++)

Please post a schematic so we can try and spot your error.

Hope this will be useful.

I prefer this because this explicitly shows that I iterate over all possible triplets of 0 and 1.

for (int i = 0b000; i <= 0b111; i++)

I prefer this because this explicitly shows that I iterate over all possible triplets of 0 and 1.

And in some way using 0 to 7 doesn't?

  1. That is not a schematic, it is a physical layout diagram otherwise known as a Fritzing abortion.

  2. In your code you use pins 2,3 & 4 for the address select, on your "diagram" you use pins 1,2 & 3

  3. You have no decoupling capacitor on the 4051 chip

Thanks for answer.

  1. Sorry for wrong schema.
  2. Made a mistake on diagram. When I test I connect to pins 2, 3, 4.
  3. I don't know what decoupling capacitor is. I haven't seen it on any diagram with CD4051 and Arduino tutorial doesn't mention it. I've just read about decoupling capacitor but don't know where to put it. Should I put it between CD4051 output pin and A0?

See
http://www.thebox.myzen.co.uk/Tutorial/De-coupling.html
You put a 0.1uF ceramic capacitor between the power and ground of each chip you use as close to the chip as possible with as short a lead as possible.

You could also try reading the analogue input twice once the multiplex pins have been set and using the second value you get.

Thank you. I will look into it.