UP | HOME

Map scancodes to keycodes

Scancodes vs keycodes

  • Scancode: the keyboard sends a scancode to the computer.
  • Keycode: the kernel maps the scancode to a keycode.

Mapping

Get the scancodes

Run the following command as root:

evtest

And select the input device that corresponds to the keyboard. Then, press the keys that you want to map. For instance,

Event: time 1753187771.746790, type 4 (EV_MSC), code 4 (MSC_SCAN), value 70004
Event: time 1753187771.746790, type 1 (EV_KEY), code 30 (KEY_A), value 

The previous output shows that the scancode for the a key is 70004.

Get the device modalias

If the selected device is, for instance, /dev/input/event6, then get the modalias with the following command:

cat /sys/class/input/event6/device/modalias

The output should be similar to this:

input:b0003v0853p0146e0111-e0,1,4,11,...

We will need it to create the hwdb file.

Create a hwdb file

Create a file named /etc/udev/hwdb.d/99-keyboard.hwdb. The content for the previous example should be similar to this:

# Topre REALFORCE 87 US
# Input device ID: bus 0x03 vendor 0x853 product 0x146 version 0x111
evdev:input:b0003v0853p0146e0111*
 KEYBOARD_KEY_700e0=leftmeta  # leftctrl  -> leftmeta
 KEYBOARD_KEY_700e3=leftalt   # leftmeta  -> leftalt
 KEYBOARD_KEY_700e2=leftctrl  # leftalt   -> leftctrl
 KEYBOARD_KEY_700e6=rightctrl # rightalt  -> rightctrl
 KEYBOARD_KEY_700e7=rightalt  # rightmeta -> rightalt
 KEYBOARD_KEY_700e4=rightmeta # rightctrl -> rightmeta

It is a list of records with the following format:

<modalias pattern>
 KEYBOARD_KEY_<scancode>=<keycode>
 ...

The scancode should be expressed in hex lowercase. The keycodes are retrieved and normalized from the kernel input API header. Keycodes are either KEY_* defines in lowercase with the key_ prefix optionally removed or BTN_ defines in lowercase with btn_ preserved.

See hwdb(7) and 60-keyboard.hwdb for more details.

Update the binary hwdb

Run the following command as root:

systemd-hwdb update

Reload the binary hwdb

Run the following command as root:

udevadm trigger

Date: 2025-07-22 Tue 00:00

Author: Roi Martin

Created: 2025-07-22 Tue 16:55

Validate