Try Embedded

Eight analog inputs on one pin (CD4051)

A CD4051 multiplexer picks one of eight analog signals for a single analog pin: read four knobs through it, one channel at a time.

Logic · Intermediate

In a real product: Mixing console (Consumer electronics): A multiplexer reads dozens of faders and knobs with one analog input.

Out of analog pins? A CD4051 is an analog switch with eight positions: three digital pins choose which channel is joined to its COM pin, and COM goes to one analog input. Scanning the channels reads eight signals through one pin.

What you'll learn

  • Selecting a channel with a 3-bit binary number on A, B and C
  • Waiting a moment after switching before reading
  • That a multiplexer is a real switch: signals go either way through it

How it works

For channel n, A is bit 0, B bit 1 and C bit 2: channel 5 is C=1, B=0, A=1. The sketch writes those three pins, waits 10 µs for the switch to settle, then reads A0. INH is tied to GND (HIGH would open every channel), and VEE to GND for signals between 0 V and 5 V. Four knobs are on channels 0, 2, 5 and 7; the others read whatever floats there.

Try this

  • Turn each knob and watch only its channel change.
  • Wire an LED from channel 3 to GND, make A0 an output and write HIGH with channel 3 selected: the switch passes it the other way.
  • Chain a second CD4051 sharing A, B and C, with its COM on A1: sixteen inputs from five pins.

sketch.ino

// Four knobs read through a CD4051: A, B, C on pins 2, 3, 4 choose the channel; COM to A0. Prints channels 0-7 every
// half second.
const int SELECT[] = {2, 3, 4};  // A, B, C

int readChannel(int ch) {
  for (int b = 0; b < 3; b++) digitalWrite(SELECT[b], (ch >> b) & 1);
  delayMicroseconds(10);
  return analogRead(A0);
}

void setup() {
  Serial.begin(9600);
  for (int pin : SELECT) pinMode(pin, OUTPUT);
}

void loop() {
  for (int ch = 0; ch < 8; ch++) {
    Serial.print("CH");
    Serial.print(ch);
    Serial.print(' ');
    Serial.print(readChannel(ch));
    Serial.print(ch < 7 ? "  " : "\n");
  }
  delay(500);
}

Lessons behind it