### Full Example with Combo Layers Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/combo_layers.md This example demonstrates a complete KMK keyboard setup including combo layers. Ensure `Layers` is imported and the `combo_layers` dictionary is defined before appending it to `keyboard.modules`. ```python import board from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC combo_layers = { (1, 2): 3, } keyboard = KMKKeyboard() keyboard.modules.append(Layers(combo_layers)) keyboard.keymap = [ [ #Default KC.A, KC.B KC.C KC.D, KC.E, KC.F KC.G KC.H, KC.MO(1), KC.J, KC.K, KC.MO(2), ], [ #Layer 1 KC.N1, KC.N2, KC.N3, KC.N4, KC.N5, KC.N6, KC.N7, KC.N8, KC.MO(1), KC.N9, KC.N0, KC.MO(2), ], [ #Layer 2 KC.EXLM, KC.AT, KC.HASH KC.DLR, KC.PERC, KC.CIRC, KC.AMPR KC.ASTR, KC.MO(1), KC.LPRN, KC.RPRN, KC.MO(2), ], [ #Layer 3 KC.F1, KC.F2, KC.F3, KC.F4, KC.F5, KC.F6, KC.F7, KC.F8, KC.MO(1) KC.F9, KC.F10, KC.MO(2) ] ] if __name__ == '__main__': keyboard.go() ``` -------------------------------- ### Complete Keyboard Configuration Example Source: https://context7.com/kmkfw/kmk_firmware/llms.txt A comprehensive setup for a split 42-key keyboard, integrating multiple modules like Layers, HoldTap, Split, Macros, EncoderHandler, RGB lighting, and MediaKeys. ```python import board from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC from kmk.scanners import DiodeOrientation from kmk.modules.layers import Layers from kmk.modules.holdtap import HoldTap from kmk.modules.split import Split, SplitSide from kmk.modules.macros import Macros from kmk.modules.encoder import EncoderHandler from kmk.extensions.RGB import RGB, AnimationModes from kmk.extensions.media_keys import MediaKeys # Initialize keyboard keyboard = KMKKeyboard() # Matrix configuration keyboard.col_pins = (board.GP2, board.GP3, board.GP4, board.GP5, board.GP6, board.GP7) keyboard.row_pins = (board.GP14, board.GP15, board.GP16, board.GP17) keyboard.diode_orientation = DiodeOrientation.COLUMNS ``` -------------------------------- ### Configure LED Key Positions and Settings Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/peg_rgb_matrix.md Example configuration for kb.py in a non-split keyboard setup. Defines LED key positions, brightness limit, and total number of pixels. Ensure `led_key_pos` matches your board's LED layout. ```python led_key_pos=[ 10,11,12,13,14,15,16,17,18,19, 20,21,22,23,24,25,26,27,28,29, 30,31,32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4 ] brightness_limit = 1.0 num_pixels = 48 ``` -------------------------------- ### Basic KMK Keyboard Setup Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/Getting_Started.md This snippet demonstrates the minimal configuration required to get a KMK keyboard running. Ensure CircuitPython 7.3+ is installed and adapt GP0/GP1 pins to your board's matrix. ```python print("Starting") import board from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC from kmk.scanners import DiodeOrientation keyboard = KMKKeyboard() keyboard.col_pins = (board.GP0,) keyboard.row_pins = (board.GP1,) keyboard.diode_orientation = DiodeOrientation.COL2ROW keyboard.keymap = [ [KC.A,] ] if __name__ == '__main__': keyboard.go() ``` -------------------------------- ### Analogio with AnalogKeys Example Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/analogin.md Example demonstrating how to use AnalogInputs with AnalogKeys to map analog inputs from board.A0, A1, and A2 to keyboard keys. It shows how to set different thresholds for AnalogKeys. ```python import board from analogio import AnalogIn from kmk.modules.analogin import AnalogInput, AnalogInputs from kmk.modules.analogin.keys import AnalogKey analog = AnalogInputs( [ AnalogInput(AnalogIn(board.A0)), AnalogInput(AnalogIn(board.A1)), AnalogInput(AnalogIn(board.A2)), ], [ [AnalogKey(KC.X), AnalogKey(KC.Y), AnalogKey(KC.Z)], [KC.TRNS, KC.NO, AnalogKey(KC.W, threshold=96)], ], ) keyboard.modules.append(analog) ``` -------------------------------- ### Full KMK Encoder Example (Python) Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/encoder.md This comprehensive example demonstrates how to configure a single rotary encoder with KMK firmware, including pin assignments, diode orientation, and basic layer setup. It also shows how to integrate media keys. ```python import board from kmk.kmk_keyboard import KMKKeyboard from kmk.consts import UnicodeMode from kmk.keys import KC from kmk.scanners import DiodeOrientation from kmk.modules.layers import Layers from kmk.modules.encoder import EncoderHandler from kmk.extensions.media_keys import MediaKeys keyboard = KMKKeyboard() layers = Layers() encoder_handler = EncoderHandler() keyboard.modules = [layers, encoder_handler] keyboard.extensions.append(MediaKeys()) keyboard.col_pins = ( board.GP0, board.GP1, board.GP2, board.GP3, board.GP4, board.GP5, board.GP6, board.GP7, board.GP8, board.GP9, board.GP10, board.GP11, board.GP12, board.GP13, ) keyboard.row_pins = (board.GP28, board.GP27, board.GP22, board.GP26, board.GP21) keyboard.diode_orientation = DiodeOrientation.COLUMNS # I2C example #import busio #SDA = board.GP0 #SCL = board.GP1 #i2c = busio.I2C(SCL, SDA) #encoder_handler.i2c = ((i2c, 0x36, False),) # encoder_handler.divisor = 2 # for encoders with more precision encoder_handler.pins = ((board.GP17, board.GP15, board.GP14, False),) # Filler keys _______ = KC.TRNS xxxxxxx = KC.NO tbdtbd = KC.A # Layers LYR_STD, LYR_EXT, LYR_NUM, LYR_GAME = 0, 1, 2, 3 TO_STD = KC.DF(LYR_STD) MT_EXT = KC.MO(LYR_EXT) TO_NUM = KC.MO(LYR_NUM) TO_GAME = KC.DF(LYR_GAME) ``` -------------------------------- ### Example Layer Keymap Configuration Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/layers.md Demonstrates setting up a two-layer keymap for a 3x3 macropad. This example includes definitions for momentary, modifier, and layer-tap keycodes, and assigns them to specific keys on the base and function layers. ```python from kmk.modules.layers import Layers keyboard.modules.append(Layers()) # Layer Keys MOMENTARY = KC.MO(1) MOD_LAYER = KC.LM(1, KC.RCTL) LAYER_TAP = KC.LT(1, KC.END, prefer_hold=True, tap_interrupted=False, tap_time=250) # any tap longer than 250ms will be interpreted as a hold keyboard.keymap = [ # Base layer [ KC.NO, KC.UP, KC.NO, KC.LEFT, KC.DOWN, KC.RGHT, MOMENTARY, LAYER_TAP, MOD_LAYER, ], # Function Layer [ KC.F1, KC.F2, KC.F3, KC.F4, KC.F5, KC.F6, KC.TRNS, KC.TRNS, KC.TRNS, ], ] ``` -------------------------------- ### Initialize and Run KMK Firmware Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/encoder.md This is the standard entry point for the KMK firmware. It initializes the keyboard and starts the main event loop. ```python if __name__ == "__main__": keyboard.go() ``` -------------------------------- ### Basic KMK Keyboard Setup Source: https://context7.com/kmkfw/kmk_firmware/llms.txt Configure the core KMKKeyboard class with matrix pins, row pins, diode orientation, and a basic keymap. This is the foundational setup for any KMK keyboard. ```python import board from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC from kmk.scanners import DiodeOrientation keyboard = KMKKeyboard() # Define the matrix pins keyboard.col_pins = (board.GP0, board.GP1, board.GP2, board.GP3) keyboard.row_pins = (board.GP4, board.GP5, board.GP6) keyboard.diode_orientation = DiodeOrientation.COL2ROW # Define the keymap (list of layers, each layer is a flat list of keys) keyboard.keymap = [ # Layer 0 - Base layer (4 cols x 3 rows = 12 keys) [ KC.ESC, KC.Q, KC.W, KC.E, KC.TAB, KC.A, KC.S, KC.D, KC.LSFT, KC.Z, KC.X, KC.C, ], ] if __name__ == '__main__': keyboard.go() ``` -------------------------------- ### Import Nice Nano Pinout Source: https://github.com/kmkfw/kmk_firmware/blob/main/boards/dactyl_manuform/README.md Example of importing the pinout configuration for the Nice Nano microcontroller. Replace `helios` with `nice_nano` for this controller. ```python from kmk.quickpin.pro_micro.nice_nano import pinout as pins ``` -------------------------------- ### Setup Macros Module Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/macros.md Import and initialize the Macros module, then add it to the keyboard's modules list. This enables the KC.MACRO() keycode. ```python from kmk.modules.macros import Macros macros = Macros() keyboard.modules.append(macros) ``` -------------------------------- ### Sticky Key Stacking Example Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/sticky_keys.md Demonstrates stacking sticky keys. Tapping a sticky key within the release timeout of another will reset the timeout of previous sticky keys and combine their effects. This example shows Ctrl+Shift+Tab. ```python SK_LCTL = KC.SK(KC.LCTL) SK_LSFT = KC.SK(KC.LSFT) keyboard.keymap = [[SK_LSFT, SK_LCTL, KC.TAB]] ``` -------------------------------- ### Define Pro Micro RP2040 Pinout for Quickpin Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/quickpin.md This is an example of how to define the pinout for a Pro Micro RP2040 board to be used with Quickpin. Pins are listed anticlockwise starting from the top left, with the chip facing towards you and USB facing up. Unaddressable pins should be set to `None`. ```python import board pinout = [ board.TX, board.RX, None, # GND None, # GND board.D2, board.D3, board.D4, board.D5, board.D6, board.D7, board.D8, board.D9, board.D21, board.MOSI, board.MISO, board.SCK, board.D26, board.D27, board.D28, board.D29, None, # 3.3v None, # RST None, # GND None, # RAW ] ``` -------------------------------- ### Basic Python Print Statement Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/contributing.md A simple example demonstrating how to print 'Hello, world!' to the console. This is a standard way to verify basic Python execution. ```python print('Hello, world!') ``` -------------------------------- ### Compile and Copy KMK with Make Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/Getting_Started.md Use this command to compile KMK and additional libraries, then load the bytecode and keyboard code onto a keyboard in one go. Ensure 'make' is installed and configured. ```sh make compile copy-compiled copy-board MPY_SOURCES='kmk/ lib/' BOARD='boards/someboard' MOUNTPOINT='/media/user/someboard' ``` -------------------------------- ### Initialize Rgb_matrix_data with Custom Colors Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/peg_rgb_matrix.md Example of initializing the `Rgb_matrix_data` class with a list of key colors and underglow colors. Ensure the number of colors provided matches the expected structure. ```python Rgb_matrix_data(keys=[[249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249], [249, 249, 249]], underglow=[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255]]) ``` -------------------------------- ### Initialize Trackball with I2C Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/pimoroni_trackball.md Declare the I2C bus and add the Trackball module to your keyboard. This setup works with both `busio` and `bitbangio`. ```python from kmk.modules.pimoroni_trackball import Trackball, TrackballMode import busio as io i2c = io.I2C(scl=board.D3, sda=board.D2) trackball = Trackball(i2c) keyboard.modules.append(trackball) ``` -------------------------------- ### Basic RGB Extension Setup Source: https://context7.com/kmkfw/kmk_firmware/llms.txt Configure the RGB extension for NeoPixel/WS2812 LEDs. Specify the data pin, number of pixels, color order, and default brightness/saturation/hue. Sets the initial animation mode. ```python import board from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC from kmk.extensions.RGB import RGB, AnimationModes keyboard = KMKKeyboard() # Basic RGB setup rgb = RGB( pixel_pin=board.GP16, # Data pin connected to LEDs num_pixels=27, # Number of LEDs rgb_order=(1, 0, 2), # GRB order for WS2812 hue_default=0, # Default hue (0=red, 85=green, 170=blue) sat_default=255, # Default saturation val_default=100, # Default brightness val_limit=255, # Maximum brightness hue_step=10, # Hue change per keypress sat_step=17, # Saturation change per keypress val_step=17, # Brightness change per keypress animation_speed=1, # Animation speed (1-10) animation_mode=AnimationModes.RAINBOW, # Initial animation breathe_center=1.5, # Breathing animation curve knight_effect_length=4, # Knight rider LED count ) keyboard.extensions.append(rgb) ``` -------------------------------- ### Full Rgb_matrix Configuration for Split Keyboard Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/peg_rgb_matrix.md A comprehensive example initializing the `Rgb_matrix` extension for a split keyboard, specifying per-key and underglow colors, enabling split mode, targeting the right side, and disabling auto-write. ```python rgb = Rgb_matrix(ledDisplay=Rgb_matrix_data( keys=[ [255,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55], [55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[255,55,55], [255,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55], [55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[255,55,55], [255,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55], [55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[255,55,55], [255,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[255,55,55],[255,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[55,55,55],[255,55,55], [255,55,55],[55,55,55],[55,55,55],[255,55,55],[255,55,55],[55,55,55],[55,55,55],[255,55,55]], underglow=[ [0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55],[0,0,55]] ), split=True, rightSide=True, disable_auto_write=True) ``` -------------------------------- ### External DAC with AnalogEvent Example Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/analogin.md Example showing how to use an external DAC (MCP4725) with AnalogEvent to dynamically adjust keyboard parameters like holdtap.tap_time and control RGB hue. It includes a safety check to reboot if the analog value changes too drastically. ```python # setup of holdtap and rgb omitted for brevity # holdtap = ... # rgb = ... import board import busio import adafruit_mcp4725 from kmk.modules.analogin import AnalogEvent, AnalogInput, AnalogInputs i2c = busio.I2C(board.SCL, board.SDA) dac = adafruit_mcp4725.MCP4725(i2c) def adj_ht_taptime(self, event, keyboard): holdtap.tap_time = event.value if abs(event.change) > 100: import microcontroller microcontroller.reset() HTT = AnalogEvent( on_change=adj_ht_taptime, on_stop=lambda self, event, keyboard: rgb.increase_hue(16), ) a0 = AnalogInput(dac, lambda _: int(_.value / 0xFFFF * 1980) + 20) analog = AnalogInputs( [a0], [[HTT]], ) keyboard.modules.append(analog) ``` -------------------------------- ### Select Nice!Nano v2 MCU Pinout Source: https://github.com/kmkfw/kmk_firmware/blob/main/boards/fingerpunch/ffkb/README.md Use this line in `kb.py` when using a Nice!Nano v2 MCU. Note that the Nice!Nano has limited ROM, requiring additional setup steps. ```python nice_nano/kb.py ``` -------------------------------- ### Initialize RGB Extension with Multiple PixelBuffers Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/rgb.md This example shows how to initialize the RGB extension with multiple PixelBuffer objects, such as Neopixel, DotStar, and a custom buffer. The `pixel_pin` is set to `None` when providing custom pixel buffers. ```python from kmk.extensions.RGB import RGB pixels = ( Neopixel(...), DotStar(...), CustomPixelBuf(...) ) rgb = RGB(pixel_pin=None, pixels=pixels) keyboard.extensions.append(rgb) ``` -------------------------------- ### Configure Split Keyboard with Rotary Encoder Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/scanners.md This example demonstrates how to set up a split keyboard with a rotary encoder. It initializes the Split class with specific arguments and configures both MatrixScanner and RotaryioEncoder. ```python from kmk.scanners import DiodeOrientation from kmk.scanners.keypad import MatrixScanner from kmk.scanners.encoder import RotaryioEncoder from kmk.modules.split import Split class MyKeyboard(KMKKeyboard): def __init__(self) -> None: super().__init__() self.diode_orientation = DiodeOrientation.ROW2COL split_args = { 'split_side': None, # EE Hands 'data_pin': board.GP1, 'data_pin2': board.GP0, 'split_flip': True, 'use_pio': True, 'uart_flip': True, 'add_buttons': 2 # add left- and right-turn actions for one encoder on each side; see `split_keyboards.md` } self.row_pins = (board.GP2, board.GP3, board.GP4, board.GP5, board.GP6) self.col_pins = (board.GP29, board.GP28, board.GP27, board.GP26, board.GP22, board.GP20) self.split = Split(**split_args) self.modules.append(self.split) matrix = MatrixScanner(row_pins=self.row_pins, column_pins=self.col_pins, columns_to_anodes=DiodeOrientation.ROW2COL) rotary = RotaryioEncoder(pin_a=board.D7, pin_b=board.D8) self.matrix = [ matrix, rotary ] if __name__ == '__main__': keyboard = MyKeyboard() keyboard.go() ``` -------------------------------- ### Using Stringy Keymaps Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/extension_stringy_keymaps.md Demonstrates how to integrate and use the StringyKeymaps extension to define a keymap using string names for keys. This setup allows for mixed usage of string names and standard keycodes. ```python from kmk.extensions.stringy_keymaps import StringyKeymaps # Normal # keyboard.keymap = [[ KC.A, KC.B, KC.RESET ]] # Indexed # keyboard.keymap = [[ KC['A'], KC['B'], KC['RESET'] ]] # String names mixed with normal keycodes # keyboard.keymap = [[ 'A' , KC.B, KC.RESET ]] # String names keyboard.keymap = [[ 'A' , 'B', 'RESET' ]] stringyKeymaps = StringyKeymaps() keyboard.extensions.append(stringyKeymaps) ``` -------------------------------- ### Define a Simple Keymap Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/config_and_keymap.md Assign a keymap to your keyboard instance. This example shows a basic keymap with two keys on a single layer. Use `KC.NO` for empty positions in the matrix. ```python keyboard.keymap = [[KC.A, KC.B]] ``` -------------------------------- ### RGB Layer Indication with Python Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/layers.md Implement RGB background or status LED color changes based on the active keyboard layer. This example requires the `board` and `kmk.extensions.rgb` modules. Ensure your `pixel_pin` and `num_pixels` are correctly configured for your hardware. The `rgb_order` may need adjustment based on your specific LED strip. ```python import board from kmk.extensions.rgb import RGB from kmk.modules.layers import Layers class LayerRGB(RGB): def on_layer_change(self, layer): if layer == 0: self.set_hsv_fill(0, self.sat_default, self.val_default) # red elif layer == 1: self.set_hsv_fill(170, self.sat_default, self.val_default) # blue elif layer == 2: self.set_hsv_fill(43, self.sat_default, self.val_default) # yellow elif layer == 4: self.set_hsv_fill(0, 0, self.val_default) # white # update the LEDs manually if no animation is active: self.show() rgb = LayerRGB(pixel_pin=board.GP16, # GPIO pin of the status LED, or background RGB light num_pixels=1, # one if status LED, more if background RGB light rgb_order=(0, 1, 2), # RGB order may differ depending on the hardware hue_default=0, # in range 0-255: 0/255-red, 85-green, 170-blue sat_default=255, val_default=5, ) keyboard.extensions.append(rgb) class RGBLayers(Layers): def activate_layer(self, keyboard, layer, idx=None): super().activate_layer(keyboard, layer, idx) rgb.on_layer_change(layer) def deactivate_layer(self, keyboard, layer): super().deactivate_layer(keyboard, layer) rgb.on_layer_change(keyboard.active_layers[0]) keyboard.modules.append(RGBLayers()) ``` -------------------------------- ### Initialize KMK Keyboard with RGB Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/boards/nullbitsco/tidbit/README.md Instantiate the KMKKeyboard with landscape layout and active encoders, then configure and append the RGB extension for backlighting. Ensure `pixel_pin` is correctly set. ```python from kb import KMKKeyboard from kmk.extensions.rgb import RGB, AnimationModes keyboard = KMKKeyboard(active_encoders=[0], landscape_layout=True) rgb = RGB( pixel_pin=keyboard.pixel_pin, num_pixels=8, animation_mode=AnimationModes.BREATHING, animation_speed=3, breathe_center=2, ) keyboard.extensions.append(rgb) ``` -------------------------------- ### Custom Trackball Handler Example Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/pimoroni_trackball.md An example of a custom handler that implements specific behaviors for horizontal scrolling, key holding, and middle mouse clicks. ```python from kmk.modules.pimoroni_trackball import TrackballHandler CustomHandler(TrackballHandler): def handle(self, keyboard, trackball, x, y, switch, state): if x > 0: keyboard.tap_key(KC.RIGHT) elif x < 0: keyboard.tap_key(KC.LEFT) if y != 0: AX.W.move(keyboard, y) if switch: keyboard.pre_process_key(KC.MB_MMB, is_pressed=state) ``` -------------------------------- ### Initialize Rgb_matrix Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/peg_rgb_matrix.md Shows how to import and initialize the Rgb_matrix extension with basic configuration. Ensure `Rgb_matrix` is imported from `kmk.extensions.peg_rgb_matrix`. ```python from kmk.extensions.peg_rgb_matrix import Rgb_matrix,Rgb_matrix_data,Color # ... Other code rgb = Rgb_matrix(...per key color data) keyboard.extensions.append(rgb) ``` -------------------------------- ### Initialize KMK Display Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/Display.md Initializes the main Display extension with a chosen driver and various optional parameters for screen size, orientation, and power saving. ```python from kmk.extensions.display import Display, TextEntry, ImageEntry # For all display types display = Display( # Mandatory: display=driver, # Optional: width=128, # screen size height=32, # screen size flip = False, # flips your display content flip_left = False, # flips your display content on left side split flip_right = False, # flips your display content on right side split brightness=0.8, # initial screen brightness level brightness_step=0.1, # used for brightness increase/decrease keycodes dim_time=20, # time in seconds to reduce screen brightness dim_target=0.1, # set level for brightness decrease off_time=60, # time in seconds to turn off screen powersave_dim_time=10, # time in seconds to reduce screen brightness powersave_dim_target=0.1, # set level for brightness decrease powersave_off_time=30, # time in seconds to turn off screen ) ``` -------------------------------- ### Enable BLE HID Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/ble_hid.md Use this snippet to enable BLE HID functionality. Ensure the `adafruit_ble` library is installed on your CircuitPython device. ```python from kmk.hid import HIDModes if __name__ == '__main__': keyboard.go(hid_type=HIDModes.BLE) ``` -------------------------------- ### Tap a Key via Serial ACE Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/serialace.md Execute Python code through the serial interface to simulate a key tap, for example, tapping the 'Y' key. ```bash $ echo "exec('from kmk.keys import KC; keyboard.tap_key(KC.Y)')" > /dev/ttyACM1 $ y ``` -------------------------------- ### Get Active Layers via Serial ACE Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/serialace.md Send a command to the serial interface to retrieve the list of currently active layers on the keyboard. ```bash $ echo "keyboard.active_layers" > /dev/ttyACM1 $ cat /dev/ttyACM1 ``` -------------------------------- ### Define and Configure Combos Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/combos.md This snippet demonstrates how to initialize the Combos module, define a custom key, and set up various chord and sequence combos with different configurations. ```python from kmk.keys import KC, make_key from kmk.modules.combos import Combos, Chord, Sequence combos = Combos() keyboard.modules.append(combos) make_key( names=('MYKEY',), on_press=lambda *args: print('I pressed MYKEY'), ) combos.combos = [ Chord((KC.A, KC.B), KC.LSFT), Chord((KC.A, KC.B, KC.C), KC.LALT), Chord((0, 1), KC.ESC, match_coord=True), Chord((8, 9, 10), KC.MO(4), match_coord=True), Sequence((KC.LEADER, KC.A, KC.B), KC.C), Sequence((KC.E, KC.F), KC.MYKEY, timeout=500, per_key_timeout=False, fast_reset=False) ] ``` -------------------------------- ### Enable Status LEDs Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/extension_statusled.md To enable the extension, define a list of `led_pins` and append the configured `statusLED` object to `keyboard.extensions`. This example uses three pins. ```python from kmk.extensions.statusled import statusLED import board statusLED = statusLED(led_pins=[board.GP0, board.GP1, board.GP2]) keyboard.extensions.append(statusLED) ``` -------------------------------- ### Advanced Trackball Initialization with Handlers Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/pimoroni_trackball.md Initialize the Trackball module with multiple handlers and advanced configuration like `angle_offset`. This setup allows for complex input mapping. ```python from kmk.modules.pimoroni_trackball import Trackball, TrackballMode, PointingHandler, KeyHandler, ScrollHandler, ScrollDirection trackball = Trackball( i2c, mode=TrackballMode.MOUSE_MODE, # optional: set rotation angle of the trackball breakout board, default is 1 angle_offset=1.6, handlers=[ # act like an encoder, input arrow keys, enter when pressed KeyHandler(KC.UP, KC.RIGHT, KC.DOWN, KC.LEFT, KC.ENTER), # on layer 1 and above use the default pointing behavior, left click when pressed PointingHandler(), # use ScrollDirection.NATURAL (default) or REVERSE to change the scrolling direction, left click when pressed ScrollHandler(scroll_direction=ScrollDirection.NATURAL, on_press=KC.MB_LMB) ] ) ``` -------------------------------- ### Configure I2C Encoder Pins Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/encoder.md Set up I2C encoders by defining the I2C bus, address, and inversion flag. This example assumes a specific I2C address (0x36). ```python # I2C Encoder # Setup i2c SDA = board.GP0 SCL = board.GP1 i2c = busio.I2C(SCL, SDA) encoder_handler.pins = ((i2c, 0x36, False), (encoder 2 definition), etc. ) ``` -------------------------------- ### HoldTap with Modifier Keys Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/holdtap.md Examples of using HoldTap with common modifier keys. The key performs the specified hold action when held and a placeholder 'kc' action when tapped. ```python LCTL = KC.HT(KC.SOMETHING, KC.LCTRL) ``` ```python LSFT = KC.HT(KC.SOMETHING, KC.LSFT) ``` ```python LALT = KC.HT(KC.SOMETHING, KC.LALT) ``` ```python LGUI = KC.HT(KC.SOMETHING, KC.LGUI) ``` ```python RCTL = KC.HT(KC.SOMETHING, KC.RCTRL) ``` ```python RSFT = KC.HT(KC.SOMETHING, KC.RSFT) ``` ```python RALT = KC.HT(KC.SOMETHING, KC.RALT) ``` ```python RGUI = KC.HT(KC.SOMETHING, KC.RGUI) ``` ```python SGUI = KC.HT(KC.SOMETHING, KC.LSHFT(KC.LGUI)) ``` ```python LCA = KC.HT(KC.SOMETHING, KC.LCTRL(KC.LALT)) ``` ```python LCAG = KC.HT(KC.SOMETHING, KC.LCTRL(KC.LALT(KC.LGUI))) ``` ```python MEH = KC.HT(KC.SOMETHING, KC.LCTRL(KC.LSFT(KC.LALT))) ``` ```python HYPR = KC.HT(KC.SOMETHING, KC.HYPR) ``` -------------------------------- ### Initialize and Use KMK Debug Utility Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/debugging.md Instantiate the Debug utility with the current file as the origin. Use the `debug.enabled` guard clause before logging messages to ensure output only occurs when debugging is active. ```python from kmk.utils import Debug # Create a debug source with the current file as message origin debug = Debug(__name__) # For completeness: Force enable/disable debug output. This is handled # automatically -- you will most likely never have to use this: # debug.enabled = True/False # KMK idiomatic debug with guard clause var = 'concatenate' if debug.enabled: debug('Arguments ', var, '!') ``` -------------------------------- ### Bluetooth Split Keyboard Configuration Source: https://context7.com/kmkfw/kmk_firmware/llms.txt Configure a two-piece split keyboard for wireless communication using Bluetooth (BLE). This setup omits the need for physical wires between the halves. ```python # For Bluetooth split (no wires between halves): # split = Split(split_type=SplitType.BLE, split_side=SplitSide.LEFT) ``` -------------------------------- ### Enable LED Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/led.md Initialize the LED extension by specifying the LED pin(s) and adding it to the keyboard extensions. Requires `kmk.extensions.LED` and `board` modules. ```python from kmk.extensions.LED import LED import board led = LED(led_pin=[board.GP0, board.GP1]) keyboard.extensions.append(led) ``` -------------------------------- ### Run KMK Keyboard Instance Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/config_and_keymap.md This block is essential for initializing and running the KMK keyboard instance. Ensure it's placed at the end of your configuration file. ```python if __name__ == '__main__': keyboard.go() ``` -------------------------------- ### Configure LED Extension Defaults Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/led.md Set default values for the LED extension upon keyboard boot. This includes brightness, animation mode, speed, and other parameters. Requires `kmk.extensions.led.AnimationModes`. ```python from kmk.extensions.led import AnimationModes led = LED( led_pin=led_pin, brightness=50, brightness_step=5, brightness_limit=100, breathe_center=1.5, animation_mode=AnimationModes.STATIC, animation_speed=1, user_animation=None, val=100, ) ``` -------------------------------- ### Disable Boot Configuration with a Dedicated Switch Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/boot.md This example shows how to use a dedicated switch connected to ground to disable boot configuration. Ensure the sense pin is correctly configured. ```python import board from kmk.bootcfg import bootcfg bootcfg(sense=board.GP22, ...) ``` -------------------------------- ### Initialize KMK Keyboard with Display Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/Display.md Sets up a KMK keyboard with a display extension, configuring an I2C bus and an SSD1306 driver. It defines multiple `TextEntry` objects for layer and status indicators, including inverted text for specific layers. ```python import board import busio from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC from kmk.scanners import DiodeOrientation from kmk.modules.layers import Layers from kmk.extensions.display import Display, SSD1306, TextEntry, ImageEntry keyboard = KMKKeyboard() layers = Layers() keyboard.modules.append(layers) i2c_bus = busio.I2C(board.GP21, board.GP20) display_driver = SSD1306( i2c=i2c_bus, # Optional device_addres argument. Default is 0x3C. # device_address=0x3C, ) display = Display( display=display_driver, entries=[ TextEntry(text='Layer: ', x=0, y=32, y_anchor='B'), TextEntry(text='BASE', x=40, y=32, y_anchor='B', layer=0), TextEntry(text='NUM', x=40, y=32, y_anchor='B', layer=1), TextEntry(text='NAV', x=40, y=32, y_anchor='B', layer=2), TextEntry(text='0 1 2', x=0, y=4), TextEntry(text='0', x=0, y=4, inverted=True, layer=0), TextEntry(text='1', x=12, y=4, inverted=True, layer=1), TextEntry(text='2', x=24, y=4, inverted=True, layer=2), ], # Optional width argument. Default is 128. # width=128, height=64, dim_time=10, dim_target=0.2, off_time=1200, brightness=1, ) keyboard.extensions.append(display) ``` -------------------------------- ### Initialize and Configure RapidFire Module Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/rapidfire.md Import the RapidFire module and append it to the keyboard's modules list. This snippet shows how to set up the module for use in your KMK firmware configuration. ```python from kmk.modules.rapidfire import RapidFire keyboard.modules.append(RapidFire()) ``` -------------------------------- ### Configure KMK Extensions Source: https://context7.com/kmkfw/kmk_firmware/llms.txt Sets up extensions for the KMK keyboard, such as RGB lighting and MediaKeys. RGB extension requires specifying the pixel pin and number of pixels, along with an animation mode. ```python rgb = RGB(pixel_pin=board.GP29, num_pixels=42, animation_mode=AnimationModes.RAINBOW) keyboard.extensions = [rgb, MediaKeys()] ``` -------------------------------- ### Add MediaKeys Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/media_keys.md Append the MediaKeys extension to your keyboard's extensions list to enable media key functionality. No additional setup is required beyond this import and append. ```python from kmk.extensions.media_keys import MediaKeys keyboard.extensions.append(MediaKeys()) ``` -------------------------------- ### Generator Macro for Countdown to Paste Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/macros.md A programmatic countdown macro using a generator. Each integer return value from the generator is treated as a delay in milliseconds. This example counts down and then simulates Ctrl+V to paste. ```python def countdown(count, delay_ms): def generator(keyboard): for n in range(count, 0, -1): KC[n].on_press(keyboard) yield KC[n].on_release(keyboard) yield KC.ENTER.on_press(keyboard) yield KC.ENTER.on_release(keyboard) yield delay_ms return generator COUNTDOWN_TO_PASTE = KC.MACRO( countdown(3, 1000), Tap(KC.LCTL(KC.V)), ) ``` -------------------------------- ### Initialize APA102 LEDs with RGB Extension Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/rgb.md Use this snippet to initialize APA102 LEDs with the RGB extension. Ensure `board.SCK` and `board.MOSI` are correctly defined and `_LED_COUNT` matches your LED count. `rgb_pixel_pin` can be imported or defined manually. ```python import adafruit_dotstar from kmk.extensions.RGB import RGB from kb import rgb_pixel_pin # This can be imported or defined manually _LED_COUNT=12 pixels = adafruit_dotstar.DotStar(board.SCK, board.MOSI, _LED_COUNT) rgb = RGB(pixel_pin=None, pixels=pixels) keyboard.extensions.append(rgb) ``` -------------------------------- ### Custom Coordinate Mapping for Non-Square Keyboards Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/porting_to_kmk.md Provides a custom `coord_mapping` for keyboards that are not electrically square. This example shows a mapping for a split keyboard with different numbers of columns per row. ```python coord_mapping = [ 0, 1, 2, 3, 4, 5, 24, 25, 26, 27, 28, 29, 6, 7, 8, 9, 10, 11, 30, 31, 32, 33, 34, 35, 12, 13, 14, 15, 16, 17, 36, 37, 38, 39, 40, 41, 21, 22, 23, 42, 43, 44, ] ``` -------------------------------- ### Initialize Multiple Scanners Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/scanners.md Configure multiple scanners by assigning a list of scanner instances to the KMKKeyboard.matrix attribute. KMK assumes successive scanner keys are consecutive, so you may need to supply a custom coord_mapping. ```python class MyKeyboard(KMKKeyboard): def __init__(self): super().__init__() # create and register the scanner self.matrix = [ MatrixScanner(...), KeysScanner(...), # etc... ] ``` -------------------------------- ### Trackball LED Animation Setup Source: https://github.com/kmkfw/kmk_firmware/blob/main/docs/en/pimoroni_trackball.md Integrate the trackball's RGB LED with the KMK RGB extension for animations. This requires initializing `TrackballPixel` and configuring the `RGB` extension with desired animation settings. ```python # initiate the trackball and add the library for the trackball pixel buffer from kmk.modules.pimoroni_trackball import TrackballPixel # add rgb extension with animations from kmk.extensions.rgb import RGB, AnimationModes # pass the pixel buffer to the rgb extension and declare pixel pin None pixels = TrackballPixel(trackball) # set the rgb animation configuration to your taste rgb = RGB(pixel_pin=None, num_pixels=1, pixels=pixels, hue_default=0, sat_default=255, val_default=255, hue_step=1, sat_step=0, val_step=0, animation_speed=0.5, animation_mode=AnimationModes.SWIRL, ) keyboard.extensions.append(rgb) ```