8 décembre 2011

Experiments with the Arduino - Multiplexed leds

Introduction

In a previous experiment I was controlling 5 leds using 5 outputs of the Arduino. With the help of a 4051 multiplexer it is possible to control up to 8 leds using only 3 outputs.

Basically a multiplexer is an electronic device that can send it's single input to one of it's height outputs. The active output is selected by sending a binary number from 000 to 111 to the three control pins of the multiplexer.

Wikipedia will tell you everything you ever wanted to know about multiplexers.

The schematic

This image was generated with the awesome Fritzing application.

The code

int pinA1 = 8;
int pinA2 = 9;
int pinA3 = 10;

void setup() {                

  for(int i = 1; i <= 10; i++) {
    pinMode(i, OUTPUT);
    digitalWrite(i, LOW);
  }

  digitalWrite(2, LOW);  // Ground
  digitalWrite(3, HIGH); // Power
  digitalWrite(4, HIGH); // Mux input to send to the leds
}

void ledOn(int nr)
{
  int r0 = nr & 0x01;
  int r1 = (nr >> 1) & 0x01;
  int r2 = (nr >> 2) & 0x01;

  digitalWrite(pinA1, r0);
  digitalWrite(pinA2, r1);
  digitalWrite(pinA3, r2);
}

void loop() {
  for (int j = 0; j < 8; j++) {
    ledOn(j);
    delay(50);
  }
  for (int j = 7; j >= 0; j--) {
    ledOn(j);
    delay(50);
  }
}


Demo