I am experimenting a bit on a project using the Arduino Leonardo/ATMEGA32U4 (midi control surface) and I need to connect 8 buttons to the Leonardo. However I am out of pins and I do not have any multiplexers around (and it takes some time to get some where I am right now).
However, I have many Arduino Nano's/ATMEGA328P lying around. So I was thinking that I could use one of these to temporarily emulate a 3-bit multiplexer until I get the real deal. I wrote a simple code
// Emulating a multiplexer
// Button pins
const byte inputNum = 8;
const byte inputPins[] = {5, 6, 7, 8, 9, 10, 11, 12};
// Address pins
const byte outputNum = 3;
const byte addressPins[] = {A0, A1, A2};
// Mux output
const byte outputPin = A3;
byte address;
bool value;
void setup() {
for( byte i = 0; i<inputNum; i++){
pinMode(inputPins[i], INPUT);
}
for( byte i = 0; i<outputNum; i++){
pinMode(addressPins[i], INPUT);
}
pinMode(outputPin, OUTPUT);
}
void loop() {
// Read address
bool a0 = digitalRead(addressPins[0]);
bool a1 = digitalRead(addressPins[1]);
bool a2 = digitalRead(addressPins[2]);
// Convert to byte
address = a0 + (a1 << 1) + (a2 << 2);
// Read input pin = address
value = digitalRead(inputPins[address]);
digitalWrite(outputPin, value);
}
The Leonardo will then detect the buttons pushed by using the Nano as a multiplexer. There is however a problem, when a button is pushed, the Leonardo detects several buttons as being pushed.
Doing a bit of debugging, the problem seems to be what I feared from the get-go. Since both run at 16 MHz, the Nano might be too slow. Imagine that only button 000 has been pushed, this line is HIGH but all other lines LOW. When Leonardo scans it starts with 000, and Nano outputs HIGH, then Leonardo goes on to 001, but Nano is still outputting HIGH until it can read 001 button and then output LOW. But by this time Leonardo might have already read HIGH and gone on to 002.
I have a ESP32 and a FPGA (50MHz) that I could use as my temporary multiplexer, but they run at 3.3v and 1.2v logic, respectively, and I cannot interface them with Leonardo without a level converter (which I don't have).
Is there any easy solution to this issue?
Thanks for reading.