keyboard
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 20def cardkb_0_pressed_event(kb): 21 global label, keyboard, i2c0, cardkb_0, key, update 22 key = cardkb_0.get_key() 23 update = True 24 25def setup(): 26 global label, keyboard, i2c0, cardkb_0, key, update 27 M5.begin() 28 Widgets.fillScreen(0x222222) 29 label = Widgets.Label("USB Keyboard", 73, 6, 1.0, 0x3cc7f1, 0x222222, Widgets.FONTS.DejaVu24) 30 keyboard = Keyboard() 31 i2c0 = I2C(0, scl=Pin(1), sda=Pin(2), freq=100000) 32 cardkb_0 = CardKBUnit(i2c0) 33 cardkb_0.set_callback(cardkb_0_pressed_event) 34 update = False 35 36def loop(): 37 global label, keyboard, i2c0, cardkb_0, key, update 38 M5.update() 39 cardkb_0.tick() 40 if keyboard.is_open(): 41 if update: 42 keyboard.input(str(chr(key))) 43 update = False 44 45if __name__ == '__main__': 46 try: 47 setup() 48 while True: 49 loop() 50 except (Exception, KeyboardInterrupt) as e: 51 try: 52 from utility import print_error_msg 53 print_error_msg(e) 54 except ImportError: 55 print("please update to latest firmware") 56
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

