Close

Read Keystrokes using Matrix Scanning

A project log for Lattice60

Custom Ortholinear 60-ish Percent Mechanical Keyboard

DanielDaniel 05/27/2022 at 00:170 Comments

In a previous log I have setup a breadboard with a Pro Micro and some diodes and switches to test the firmware. I was interested how the microcontroller (MCU) actually finds out if a switch is pressed and at what speed it does that. Recall that the keys are arranged in a matrix, where switches of each row and column are connected to one another. Each row and column also get assigned a pin on the MCU.

Due to the limited number of connections to the MCU, not all switches can be read at once. Instead, matrix scanning is applied. In the case of QMK, rows are read in a time-multiplexed manner, one at a time. This can be visualized by hooking up the two channels of an oscilloscope to the two rows of my 2x2 test keyboard (green cables).

The image below shows the signal captured by the scope. The upper plot belongs to row 1 and the lower one to row 2. We can observe that the signal is high by default. The pulses, which occur at a fixed rate, indicate that the respective row is being read.

The row pins are outputs of the MCU, since the pulses are present regardless of the switches being pressed or not. Accordingly, the column pins are configured as inputs. They are connected to an MCU-internal pull-up resistor. That means their input signal is high by default, except if the line is pulled to ground. And that only happens if the following two conditions are true:

  1. A row pin has been pulled low and outputs a zero
  2. A switch between this low row signal and the column input has been pressed

A schematic of the 2x2 keyboard should make that clearer. In the below example, switch (1,1) is pressed. When row 1 is scanned (by pulling the line to zero), the inputs read 0 and 1 for the two columns, respectively. For row 2, both inputs are pulled high by the resistor since no switches are pressed. This way, the controller can work out the coordinates of the pressed switches.

But how fast is this whole procedure? Using the cursors on the oscilloscope, we can determine the time difference between subsequent pulses on a row. You can see that keys are read every 210 us or more than 4000x per second. Pretty fast! So, it's unlikely that keyboard will every miss a keystroke. The overall latency until the input is recognized by your computer is obviously much longer since it needs to be processed by the Pro Micro and the computer hardware first.

Discussions