An M×N key matrix driver.
(M is number of output pins and N is number of input pins.)
These key matrices look like this:
This is a 4×4 matrix. And here is the schematic
You can connect any M×N key matrix, theoretically, by using M+N GPIO pins.
You can also use any compatible GPIO controller like Mcp23xxx instead of native controller.
You need to create 2 lists of int, one for the input and one for the output.
IEnumerable<int> outputs = new int[] { 26, 19, 13, 6 };
IEnumerable<int> inputs = new int[] { 21, 20, 16, 12 };
KeyMatrix mk = new KeyMatrix(outputs, inputs, TimeSpan.FromMilliseconds(20));
You can use as well any GpioController like the MCP23017 in the following example
var settings = new System.Device.I2c.I2cConnectionSettings(1, 0x20);
var i2cDevice = System.Device.I2c.I2cDevice.Create(settings);
var mcp23017 = new Iot.Device.Mcp23xxx.Mcp23017(i2cDevice);
GpioController gpio = new GpioController(PinNumberingScheme.Logical, mcp23017);
IEnumerable<int> outputs = new int[] { 26, 19, 13, 6 };
IEnumerable<int> inputs = new int[] { 21, 20, 16, 12 };
KeyMatrix mk = new KeyMatrix(outputs, inputs, TimeSpan.FromMilliseconds(20), gpio, true);
To read a key, just the ReadKey
function:
KeyMatrixEvent? key = mk.ReadKey();
KeyMatrixEvent contains the event that happened. Please note that ReadKey is blocked up to the moment an event is detected.
KeyMatrix
supports events. Just subscribe to the event and have a function to handle the events:
Console.WriteLine("This will now start listening to events and display them. Press a key to finish.");
mk.KeyEvent += KeyMatrixEventReceived;
mk.StartListeningKeyEvent();
while (!Console.KeyAvailable)
{
Thread.Sleep(1);
}
mk.StopListeningKeyEvent();
void KeyMatrixEventReceived(object sender, KeyMatrixEvent keyMatrixEvent)
{
// Do something here, you have an event!
}
- Using diodes(eg. 1N4148) for each button prevents "ghosting" or "masking" problem.
- Input pins need pull-down resistors connect to ground if your MCU doesn't have it. So you need to have a pull-down on a Raspberry Pi for example.
- If your key matrix doesn't work well, try to swap output and input pins. Some includes diodes and if they are used the reverse way won't work properly.
This shows how to connect the matrix.
Important: Please make you don't forget to place a pull down on the input matrix.