Using the CD74HC4067 multiplexer with Arduino

17 Nov 2009

Multiplexer

Below is an Arduino sketch that uses the CD74HC4067 multiplexer / demultiplexer to read analog values from all 16 channels. This gives you the ability to read from 16 analog inputs while only using one analog input and four digital pins.

Download the source code.

/*
 CD74HC4067 Analog / Digital Multiplexing

 This sketch reads analog values from all 16 of the multiplexer pins.

 created 17 Nov 2009
 by Rory Nugent

 The following pins must be connected:

 Digital Pin 2 -> S0
 Digital Pin 3 -> S1
 Digital Pin 4 -> S3
 Digital Pin 5 -> S4

 Analog In Pin 0 -> SIG

 */

// Mux analog / digital signal pin
#define sig 0      // Analog In Pin 0

// Mux channel select pins
#define setPin0 2  // Digital Pin 2
#define setPin1 3  // Digital Pin 3
#define setPin2 4  // Digital Pin 4
#define setPin3 5  // Digital Pin 5

void setup()
{
  Serial.begin(9600);

  pinMode(setPin0, OUTPUT);
  pinMode(setPin1, OUTPUT);
  pinMode(setPin2, OUTPUT);
  pinMode(setPin3, OUTPUT);
}

void loop()
{
  // for loop to cycle through all mux channels, 0 - 15
  for(int i = 0; i < 16; i++)
  {
    int sigValue = readSig(i);  // read from a mux channel

    // print the analog / digital value to the serial monitor
    Serial.print(sigValue);
    Serial.print("\t");  // TAB
  }
  Serial.println();      // NEW LINE
}

// NAME: readSig
// INPUT: mux channel as an integer, 0 - 15
// RETURN: analog value of the selected mux channel as an integer
int readSig(int channel)
{
  // use the first four bits of the channel number to set the channel select pins
  digitalWrite(setPin0, bitRead(channel, 0));
  digitalWrite(setPin1, bitRead(channel, 1));
  digitalWrite(setPin2, bitRead(channel, 2));
  digitalWrite(setPin3, bitRead(channel, 3));

  // read from the selected mux channel
  int sigValue = analogRead(sig);

  // return the received analog value
  return sigValue;
}