Skip to content

Bluetooth HID Keyboard Example

Description

The Bluetooth HID Keyboard Example demonstrates how to use the Bluetooth Low Energy HID GATT Service for a keyboard.

The example code enumerates the nRF52840 M.2 Developer Kit into a Bluetooth HID keyboard that has an A key pressed by the USER button. The code depends on:

Before you start coding, the Python Interpreter should be installed on the nRF52840 M.2 module correctly:

Run the code

Run the USB HID Keyboard Example by performing the following steps:

  1. Connect the Module USB port to your PC as shown in the figure below. A disk drive called CIRCUITPY should be automatically detected by the computer:

  2. The example code depends on the adafruit_ble and adafruit_hid drivers. Download and extract them into your CIRCUITPY/lib folder. This should give you the following folder structure:

    CIRCUITPY
    ├── boot_out.txt
    ├── code.py
    └── lib
        ├── adafruit_ble
        └── adafruit_hid
    
  3. Open the code.py file on your CIRCUITPY drive, then copy and paste the following code:

    import time
    import board
    import digitalio
    import adafruit_ble
    from adafruit_ble.advertising import Advertisement
    from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
    from adafruit_ble.services.standard.hid import HIDService
    from adafruit_hid.keyboard import Keyboard
    from adafruit_hid.keycode import Keycode
    
    hid = HIDService()
    advertisement = ProvideServicesAdvertisement(hid)
    advertisement.complete_name = 'CIRCUITPY KEYBOARD'
    advertisement.appearance = 961
    ble = adafruit_ble.BLERadio()
    if ble.connected:
        for c in ble.connections:
            c.disconnect()
    ble.start_advertising(advertisement)
    advertising = True
    ble_keyboard = Keyboard(hid.devices)
    
    button = digitalio.DigitalInOut(board.USR_BTN)
    button.direction = digitalio.Direction.INPUT
    button.pull = digitalio.Pull.UP
    
    last_value = button.value
    
    while True:
        if last_value != button.value:
            last_value = button.value
            print('Button is ' + ('released' if button.value else 'pressed'))
            if ble.connected:
                if not button.value:
                    ble_keyboard.press(Keycode.A)
                else:
                    ble_keyboard.release(Keycode.A)
    
  4. Your code will run as soon as the file is done saving. A Bluetooth keyboard with the name CIRCUITPY KEYBOARD can be discovered by the host. Connect to the keyboard.

  5. Press the USER button and observe that a letter a will be sent to the host computer.

Reference

Create an Issue

Interested in contributing to this project? Want to report a bug? Feel free to click here: