Simple tool for reverse engineering key matrices

I decided to put together a tool for hooking up an arbitrary key matrix to an arduino and decode it by scanning it and reading the buttons pushed out the serial port. The gimmick I have added beyond most key decoders is I don’t care which are rows and which are columns. It was also pointed out to me that based on the information that we get over the serial port you can tell if the matrix has embedded diodes or not.

#define Start_pin          26
#define Stop_pin           49

void setup() {
  //start serial connection
  Serial.begin(115200);
  //set all pins as inputs to be read
  for (int i = Start_pin; i < (Stop_pin + 1); i++)
  {
    pinMode(i, INPUT_PULLUP);
  }
}

void loop() {
  //iterate through pins, outputting on one at a time
  for (int i = Start_pin; i < (Stop_pin + 1); i++)
  {
    pinMode(i, OUTPUT);
    digitalWrite(i, 0);
    //delay(10);  //settling time?
    //iterate throughall pins reading them as inputs
    for (int j = Start_pin; j < (Stop_pin + 1); j++)
    {
      //if the output pin is not the same pin being read and there is a connection
      if (!digitalRead(j) && i != j)
      {
        //print connection
        Serial.print("found connection: ");
        Serial.print(i);
        Serial.print(" and ");
        Serial.println(j);
      }
    }
    //set pin back to input before moving on to the next pin
    pinMode(i, INPUT_PULLUP);

  }
}

That’s all my code. I built it for use on an arduino mega so you get as many pins as possible, but it should work on anything. I set one pin at a time as an output and read all the rest in. This means that with a 21 pin matrix it could be a 20×1, 19×2, 18×3, … 12×9, or 11×10 matrix and I will still be able to decode that without knowing what it was beforehand. Since I scan both directions you will get a message like this with no diode across the switch:

found connection: 28 and 31
found connection: 31 and 28
found connection: 28 and 31
found connection: 31 and 28
found connection: 28 and 31
found connection: 31 and 28

Or this if there is a diode:

found connection: 28 and 31
found connection: 28 and 31
found connection: 28 and 31

One possible enhancement would be to use analog pins where possible and set a threshold for inputs to detect a crappy matrix that ends up as high resistance, but if that’s the case you have other problems (and I don’t have that many analog pins to use).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: