I was playing around with my new 4051 (I bought 5 and have tried this same code on each one with the same results), and can't get it to work right. A0-A2 will work correctly, but only if using delay(). I have tried this with and without pull-down resistors (10k and 1k) attached to the inputs on the 4051 and on the input pin on my Arduino. When I run this code...
void loop() {
for(int count = 0; count <=7; count++){
r0 = count & 0x01;
r1 = (count>>1) & 0x01;
r2 = (count>>2) & 0x01;
digitalWrite(2, r0);
digitalWrite(3, r1);
digitalWrite(4, r2);
val = digitalRead(readPin);
a,b,c,d,e,f,g,h =0;
if(count == 0) a=val;
if(count == 1) b=val;
if(count == 2) c=val;
if(count == 3) d=val;
if(count == 4) e=val;
if(count == 5) f=val;
if(count == 6) g=val;
if(count == 7) h=val;
}
Serial.print (a);
Serial.print (" ");
Serial.print (b);
Serial.print (" ");
Serial.print (c);
Serial.print (" ");
Serial.print (d);
Serial.print (" ");
Serial.print (e);
Serial.print (" ");
Serial.print (f);
Serial.print (" ");
Serial.print (g);
Serial.print (" ");
Serial.println (h);
...I get the number on the right (in serial monitor) when a 5v wire is touched to the pin represented by the binary number on the left:
000 - 11000000
001 - 00001100
010 - 00110000
011 - 00000011
100 - 01010101
101 - 01010101
110 - 01010101
111 - 01010101
I then wrote a new sketch (which I accidentally closed without saving and I'm not going to re-write) that had a 5 second delay after S0,S1,S2 writes, then read the input and sent the serial out. I went through and did each one manually so I could check the inputs/outputs with my voltmeter as the sketch progressed. For example, using input 2:
digitalWrite(2, 0);
digitalWrite(3, 1);
digitalWrite(4, 0); (of course I changed these values to select the correct pin)
delay(5000);
c=digitalRead(9);
Serial.print("c");
With 5v only to the pin it was supposed to read, this sketch gave the output:
000- 10000000
001- 01000000
010- 00100000
011- 00011111
100- 00001111
101- 00001111
110- 00001111
111- 00001111
I wired it up as shown in the playground (Arduino Playground - 4051), and verified on the manufacturer datasheet the the pins were the same.
Thanks in advance for any help!
-Jason