Library for a 74154 demuxer

The 74154 demuxer (or equivalents) is a 4-16 line decoder. The datasheet can be found here [link to datasheetcatalog.com]. The following is a library that can be used with an Arduino board to control the demuxer. The code is written on compiles as c99.

/*
 * 74154.h
 *
 *        Modified: Jul 22, 2009 Orlando Arias
 *                          Changed internal structure.
 *  Created on: Mar 1, 2009
 *      Author: Orlando Arias
 *     License: GPLv3
 */

#ifndef _74154_H_
#define _74154_H_

#include "WProgram.h"

/*
 * Defines a struct containing the pinout data for a 74154
 * demuxer.
 */
typedef struct {
      int pin[4];
      int G;
} Demuxer74154;

// function prototypes
void setPin(Demuxer74154 *d, int pin);
void setOff(Demuxer74154 *d);
void setOn(Demuxer74154 *d);
void initDemuxer(Demuxer74154 *d);

#endif /* _74154_H_ */
/*
 * 74154.c
 *        Modified: Jul 22, 2009 Orlando Arias
 *                          Changed internal structure.
 *  Created on: Mar 1, 2009
 *      Author: Orlando Arias
 *     License: GPLv3
 */

#include "WProgram.h"
#include "74154.h"

void setPin(Demuxer74154 *d, int pin){

      /*
       * Set pin 'pin' as high.
       * pin is a number from 0-15 inclusive which represents
       * one of the outputs of the demuxer.
       *
       * To avoid corrupting the desired output, the demuxer
       * is 'powered off' (read: all outputs are set to high)
       * before parsing the desire output.
       */
      int i=1;
      setOff(d);
      for (int a = 0; a<4; a++) {
            /*
             * The anding operation determines whether a bit
             * on a nibble is zero or one, and parses accordingly.
             *
             * Refer to the datasheet to see why this works.
             */
            digitalWrite(d->pin[a], (pin&i) ? HIGH : LOW);
            i<<=1;
      }
      setOn(d);
}

/*
 *  Doesn't really turn off the demuxer, but sets all outputs
 *  to high.
 */
void setOff(Demuxer74154 *d) {
      digitalWrite(d->G, HIGH);
}
/*
 * Sets pin on G to low.
 */
void setOn(Demuxer74154 *d){
      digitalWrite(d->G, LOW);
}

void initDemuxer(Demuxer74154 *d){
      // Initializes pinout and turns on the demuxer.
      for (int i = 0; i<4; i++)
            pinMode(d->pin[i], OUTPUT);
      pinMode(d->G, OUTPUT);
      setOn(d);
}

You can use this demuxer to drive an array of LEDs, for example. Notice that you will only be able to have one LED on at a time, however, if you were to loop rather fast (40Hz or more should do), you get the illusion that several are on at a time. I used this principle a while back to drive two seven segment displays per demuxer and made a simple digital counter.

Happy hacking!