So I'm creating this basic control pad, which involves 4x toggle switches and 4x buttons. All of the switches are connected to a single analog input and all of the buttons are connected to a separate analog input. The circuit design for both of them is pretty much identical, and looks very similar to this (basically, I just chose different resistor values):
Basically, the idea is to be able to toggle multiple buttons and switches using just 2 wires. For the most part, it works fine... IF I only read from just one of the two inputs at a time.
Here's my code in the loop:
for (int i=0;i<4;i++) {
for (int j=0;j<8;j++) {
//Buttons
if ((analogRead(A5)>analog_array[i][j]-3) && (analogRead(A5)<analog_array[i][j]+3)) {
Serial.println(i);
}
//Switches
if ((analogRead(A4)+3>analog_array[i][j]) && (analogRead(A4)-3<analog_array[i][j])) {
Serial.println(i);
}
}
}
And here's what the "analog_array" looks like:
const int analog_array[4][8] = {{ 806,825,850,858,863,869,885,893 },
{ 609,672,744,775,858,869,885,893 },
{ 560,638,744,775,850,863,885,893 },
{ 317,638,672,775,825,863,869,893 }};
So here's the specifics of the problem:
If I disable the lines of code under "//Switches", it works fine. It'll read any button combination just as I expect it would, and it'll continue to do so with any combination of the switches I toggle on or off.
HOWEVER...
If I enable the lines of code under "//Switches", suddenly, everything is broken. It will only read button presses if the 1st or 3rd switch is flipped on. It seems to always read if the 1st or 4th switch is toggled on, but it will sometimes read the 2nd or 3rd switch depending on which button I press. In other words, it seems completely arbitrary.
Here's what I tried so far:
- Adding delays in various parts of the loop
- Using different analog inputs
- Running the loops completely separately (one after the other)
- Reading the analog inputs into variables and compare them in the "if" statements that way
- Plugging the analog inputs into different pins
I'm out of ideas. This logic is pretty straight-forward. My program is only using about 6% of the Arduino's memory (I'm using an ATMega 1280).