I have a 4x2 matrix of normally closed buttons (the shop I went to didn’t have normally open buttons in stock), and I want to monitor which button is pressed at a given time. The buttons are soldered according to this video, where the left legs are soldered together as rows and the right legs are soldered together as columns.
However, what happens is that all of the buttons return an open state when pressed individually. When a whole row or column is pressed, that entire row or column reports a pressed state. I have not been able to get an individual button to report a pressed state.
All of the examples on the Internet are for normally open buttons, but I imagine that the principle is the same: give a row 5V and check each column for a connection, though in this case I would be checking to see if there is a broken connection at a given column. I don’t know how to start implementing the logic for this, though, as I haven’t found any examples of normally closed button matrices.
Any tips would be appreciated. Here is the code I am using to monitor the matrix, courtesy of baldengineer.com:
// JP1 is an input
byte rows[] = {8, 7};
const int rowCount = sizeof(rows)/sizeof(rows[0]);
// JP2 and JP3 are outputs
byte cols[] = {12, 11, 10, 9};
const int colCount = sizeof(cols)/sizeof(cols[0]);
byte keys[colCount][rowCount];
void setup() {
Serial.begin(115200);
for(int x=0; x<rowCount; x++) {
Serial.print(rows[x]); Serial.println(" as input");
pinMode(rows[x], INPUT);
}
for (int x=0; x<colCount; x++) {
Serial.print(cols[x]); Serial.println(" as input-pullup");
pinMode(cols[x], INPUT_PULLUP);
}
}
void readMatrix() {
// iterate the columns
for (int colIndex=0; colIndex < colCount; colIndex++) {
// col: set to output to low
byte curCol = cols[colIndex];
pinMode(curCol, OUTPUT);
digitalWrite(curCol, LOW);
// row: interate through the rows
for (int rowIndex=0; rowIndex < rowCount; rowIndex++) {
byte rowCol = rows[rowIndex];
pinMode(rowCol, INPUT_PULLUP);
keys[colIndex][rowIndex] = digitalRead(rowCol);
pinMode(rowCol, INPUT);
}
// disable the column
pinMode(curCol, INPUT);
}
}
void printMatrix() {
for (int rowIndex=0; rowIndex < rowCount; rowIndex++) {
if (rowIndex < 10)
Serial.print(F("0"));
Serial.print(rowIndex); Serial.print(F(": "));
for (int colIndex=0; colIndex < colCount; colIndex++) {
Serial.print(keys[colIndex][rowIndex]);
if (colIndex < colCount)
Serial.print(F(", "));
}
Serial.println("");
}
Serial.println("");
}
void loop() {
readMatrix();
printMatrix();
delay(2000);
}