Monday, November 18, 2013

Multiplexing with Arduino

Is this article you'll learn how to use a 4051 multiplexer with Arduino.

What is a multiplexer?
http://en.wikipedia.org/wiki/Multiplexer

Why should we use a mux?
 - I started a project wich required 16 button inputs, which is far more I had available to spare since my project already required many of the available pins in my Arduino Uno so I needed to work it out using fewer pins.

The sheet:



What are these pins (according to how we'll use it)?
http://playground.arduino.cc/learning/4051

For those not familiar with it here's a small explanation:
- S0, S1, S2 - The signal selector. This is plain binary. S0 = 2^0, S1 = 2^1, S2 = 2^2. So for getting y6 (110 in binary) you'd use S0=0 S1=1 S2=1.

Practical example (let's assume the 5v and gnds connected already):
- Connect 8 buttons to y0 to y7
- S0, S1 and S2 to pins 8, 9 and 10
- z to pin A0

The code:
 
//variables
int s0;
int s1;
int s2;
int count;

void setup()
{
  //4051 digital control pins
  pinMode(8, OUTPUT); // s0
  pinMode(9, OUTPUT); // s1
  pinMode(10, OUTPUT); // s2

  pinMode(A0, INPUT); // output from mux, this is an analog mux
}

void loop()
{
   for (count=0; count<=7; count++) {
   // select the bit
    s0 = bitRead(count,0);
    s1 = bitRead(count,1);
     s2 = bitRead(count,2);
    digitalWrite(2, s0);
    digitalWrite(3, s1);
    digitalWrite(4, s2); 

    if (digitalRead(A0))
    {
        //we got input on button connected to y<count> s no need to go binary now
        //your code for that here
        //the aproach I took was using arrays with the values I wanted to send to serial corresponding to each of my buttons but you can go for a typical select case statement according to your needs

    }
}


Hope it was helpful.

No comments:

Post a Comment