0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MicroPython で USB HID の使い方を調べてみる③

Posted at

はじめに

前回では、MicroPythonでキーボード風の機能を実現するためのデバイスを作成しました。今回は USB HID キーボードのプログラミングを行って完成させます。

mpremote のインストール

micropython-lib からのパッケージインストールには MicroPython プロジェクトが提供しているツール mpremote を使います。mpremotePyPI からインストールすることができて、pip を使えば簡単にPCに入れられます。

$ pip install mpremote

usb-device-keyboard パッケージのインストール

mpremote があれば、micropython-lib からのパッケージのインストールも簡単です。mip install サブコマンドでパッケージ名を指定するだけです。

$ mpremote mip install usb-device-keyboard
Install usb-device-keyboard
Installing usb-device-keyboard (latest) from https://micropython.org/pi/v2 to /lib
Installing: /lib/usb/device/__init__.mpy
Installing: /lib/usb/device/core.mpy
Installing: /lib/usb/device/hid.mpy     
Installing: /lib/usb/device/keyboard.mpy
Done                           

プログラミング

micropython-lib にあるキーボードの例を参考に、
プログラミングしてみました。

GPIO18に繋がっている青ボタンにA1キー、GPIO19に繋がっているGPIO19に左シフトキーを割り当ててます。

simple-kbd.py:

import usb.device
from usb.device.keyboard import KeyboardInterface, KeyCode, LEDCode
from machine import Pin
import time


# GPIOとキーコードのマッピング
KEYS = (
    (Pin.cpu.GPIO18, KeyCode.A),
    (Pin.cpu.GPIO19, KeyCode.LEFT_SHIFT)
)


def keyboard_example():
    # GPIOの初期化
    for pin, _ in KEYS:
        pin.init(Pin.IN, Pin.PULL_UP)

    # キーボード登録
    k = KeyboardInterface()
    usb.device.get().init(k, builtin_driver=True)

    # キー入力処理
    print("Entering keyboard loop...")
    keys = []
    prev_keys = [None]
    while True:
        if k.is_open():
            keys.clear()
            for pin, code in KEYS:
                if not pin():
                    keys.append(code)
            if keys != prev_keys:
                k.send_keys(keys)
                prev_keys.clear()
                prev_keys.extend(keys)

        time.sleep_ms(1)


keyboard_example()

できたら、Raspberry Pi Pico の Micropython のファイルシステムに main.py という名前でコピーします。

$ mpremote cp simple-kbd.py :main.py

動かしてみる

青ボタン単独で "a"、赤ボタンと青ボタンを同時に押して "A" が入力できます。

IMG_1546.gif

おわりに

以上で USB HID のキーボードインタフェースの動作を確認できました。まだ RP2* 系と samd系でしか使えないみたいですが、どちらも入手性は良いですし、安価でもありますので、あまり不自由することはないのかなと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?