键盘
usb 设备键盘
备注
当前模块只适用于 CoreS3 主机
MicroPython 应用示例
USB 键盘
1# SPDX-FileCopyrightText: 2025 M5Stack Technology CO LTD 2# 3# SPDX-License-Identifier: MIT 4import os, sys, io 5import M5 6from M5 import * 7from unit import CardKBUnit 8from usb.device.keyboard import Keyboard 9from hardware import I2C 10from hardware import Pin 11 12 13label = None 14keyboard = None 15i2c0 = None 16cardkb_0 = None 17key = None 18update = None 19 20 21def cardkb_0_pressed_event(kb): 22 global label, keyboard, i2c0, cardkb_0, key, update 23 key = cardkb_0.get_key() 24 update = True 25 26 27def setup(): 28 global label, keyboard, i2c0, cardkb_0, key, update 29 M5.begin() 30 Widgets.fillScreen(0x222222) 31 label = Widgets.Label("USB Keyboard", 73, 6, 1.0, 0x3CC7F1, 0x222222, Widgets.FONTS.DejaVu24) 32 keyboard = Keyboard() 33 i2c0 = I2C(0, scl=Pin(1), sda=Pin(2), freq=100000) 34 cardkb_0 = CardKBUnit(i2c0) 35 cardkb_0.set_callback(cardkb_0_pressed_event) 36 update = False 37 38 39def loop(): 40 global label, keyboard, i2c0, cardkb_0, key, update 41 M5.update() 42 cardkb_0.tick() 43 if keyboard.is_open(): 44 if update: 45 keyboard.input(str(chr(key))) 46 update = False 47 48 49if __name__ == "__main__": 50 try: 51 setup() 52 while True: 53 loop() 54 except (Exception, KeyboardInterrupt) as e: 55 try: 56 from utility import print_error_msg 57 58 print_error_msg(e) 59 except ImportError: 60 print("please update to latest firmware")
UIFlow2.0 案例
USB 键盘
class Keyboard
- class usb.device.keyboard.Keyboard
创建 Keyboard 对象
UIFlow2.0

- Keyboard.set_modifiers(right_gui: bool = False, right_alt: bool = False, right_shift: bool = False, right_ctrl: bool = False, left_gui: bool = False, left_alt: bool = False, left_shift: bool = False, left_ctrl: bool = False)
设置修饰键
right_gui右侧 GUI 按键的状态。True 表示该按键已被按下。right_alt右侧 Alt 键的状态。True 表示该键已被按下。right_shift右侧 Shift 键的状态。True 表示该键已被按下。right_ctrl右侧 Ctrl 键的状态。True 表示该键已被按下。left_gui左侧 GUI 按键的状态。True 表示该按键已被按下。left_alt左侧 Alt 键的状态。True 表示该键已被按下。left_shift左侧 Shift 键的状态。True 表示该键已被按下。left_ctrl左侧 Ctrl 键的状态。True 表示该键已被按下。
- Note:
需要调用 Keyboard.send_report() 后生效
UIFlow2.0

- Keyboard.set_keys(k0: int = 0, k1: int = 0, k2: int = 0, k3: int = 0, k4: int = 0, k5: int = 0)
按下指定按键(最多一次输入6个键值)
k0~k5输入为标准 HID 键值,详情参考 class KeyCode()
- Note:
需要调用 Keyboard.send_report() 后生效
输入小写 ‘a’
Keyboard.set_keys(k0=KeyCode.A) Keyboard.send_report() Keyboard.set_keys(k0=0) Keyboard.send_report()
输入大写 ‘A’
Keyboard.set_modifiers(right_shift=True) Keyboard.set_keys(k0=KeyCode.A) Keyboard.send_report() Keyboard.set_modifiers(right_shift=False) Keyboard.set_keys(k0=0) Keyboard.send_report()
UIFlow2.0

- Keyboard.send_report()
发送键盘状态报告
UIFlow2.0

- Keyboard.input(key)
输入键值
key支持 ASCII 范围字符串,或者使用 KeyCode
example:
Keyboard.input("Hello M5") Keyboard.input(KeyCode.A)
UIFlow2.0

