GPIO as Keyboard on Linux
The Linux kernel provides the gpio-keys
driver (CONFIG_KEYBOARD_GPIO
) that can map GPIO pins to keyboard keys and expose them to userspace as input devices.
Minimal device tree overlay fragment example:
&{/} {
gpio_keys {
compatible = "gpio-keys";
#address-cells = <1>;
#size-cells = <0>;
enter_button {
label = "enter";
linux,code = <KEY_ENTER>;
gpios = <&gpio1 2 GPIO_ACTIVE_HIGH>;
};
};
};
Check your board documentation and device tree for GPIO controller names, indexes, and mapping to physical pins. You might also need to adjust pinctrl for multiplexing and pin configuration.
Install the device tree overlay and reboot. If the gpio_keys
driver is present and has valid configuration specified via device tree, you should see the following line in the dmesg
output:
[ 15.218705] input: gpio_keys as /devices/platform/gpio_keys/input/input1
Next, check with evtest
if asserting the physical pin produces the desired input events:
sudo evtest /dev/input/event1
Input driver version is 1.0.1
Input device ID: bus 0x19 vendor 0x1 product 0x1 version 0x100
Input device name: "gpio_keys"
Supported events:
Event type 0 (EV_SYN)
Event type 1 (EV_KEY)
Event code 28 (KEY_ENTER)
Properties:
Testing ... (interrupt to exit)
Event: time 1753802383.310602, type 1 (EV_KEY), code 28 (KEY_ENTER), value 1
Event: time 1753802383.310602, -------------- SYN_REPORT ------------
Event: time 1753802383.870663, type 1 (EV_KEY), code 28 (KEY_ENTER), value 0
Event: time 1753802383.870663, -------------- SYN_REPORT ------------
Additionally, gpio_keys
-defined buttons can be configured to serve as wakeup sources, which can wake up the system from sleep, if supported by the board. More information is available in the kernel documentation.