I just bought a bunch of low cost 4051 analog multiplexers for use with my Arduino. I am working on a MIDI controller so I will need a lot of input both digital and analogical ones, so the multiplexers will come in handy to do analog reading using as few of the analog pins as possible.
As a first test I tried an adapter for a C64 keyboard, which has all keys placed in a 8×8 matrix of buttons.
The idea came from arduino playground where they explain the usage of multiplexers. The following image fits the c64 keyboard like a glove, so just go ahead and build the one on the right.
Link to more details: http://www.arduino.cc/playground/Learning/4051
Here is my solution. It’s the same circuit only on a perforated board. If you have the skills to make PCB-s, I really suggest to doing so.
And now for the code:
int v=0;
void setup() {
Serial.begin(9600);
Serial.print(“Hello”);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(13,INPUT);
}
byte bin[] = {
0,1,10,11,100,101,110,111};
int readKeyboard() {
int i,j,row,col,v, code;
byte r0,r1,r2;
code=0;
for(i=0;i<8;i++) {
for(j=0;j<8;j++) {
code++;
// address X
row = bin[j];
r0 = row & 0x01;
r1 = (row>>1) & 0x01;
r2 = (row>>2) & 0x01;
digitalWrite(2, r0);
digitalWrite(3, r1);
digitalWrite(4, r2);
// address Y
col = bin[i];
r0 = col & 0x01;
r1 = (col>>1) & 0x01;
r2 = (col>>2) & 0x01;
digitalWrite(5, r0);
digitalWrite(6, r1);
digitalWrite(7, r2);
// Read the actual Value
v = digitalRead(13);
/*
Serial.print(“(“);
Serial.print(j);
Serial.print(“:”);
Serial.print(i);
Serial.print(“)-“);
Serial.println(v);
*/
if(v==LOW) {
// instead of returning, you may use a buffer or whatever to keep track of all pressed keys
return code;
}
}
}
}
void loop() {
v = readKeyboard();
if(v>0) {
Serial.println(v);
}
delay(100);
}
Notes: make sure you click the SerialMonitor so you see some output. The above code will output the number of the key pressed.
For more information concerning the keyboard layout of the c64 here is a schematic of the key matrix.
(click the image to enlarge)