分页: 1 / 1

【SAMR21新玩法】34. 模拟USB鼠标键盘

发表于 : 2019年 10月 25日 10:07
shaoziyang
和MicroPython一样,在CircuitPython中,可以非常容易的模拟USB HID设备,可以将设备作为USB键盘或者USB鼠标。先看一下USB HID的基本用法:

代码: 全选

import usb_hid

kb = usb_hid.devices[0]
kb.send_report(buf)

buf是bytes或者bytearray类型,对于键盘,需要发送8字节的数据,而对于鼠标,需要发送4字节数据。

具体的使用如下,USB键盘

代码: 全选

import usb_hid
from time import sleep

kb = usb_hid.devices[0]

def kb_send(chr, shift=0):
    buf=bytearray(8)
    buf[2] = chr
    buf[0] = shift
    kb.send_report(buf)
    sleep(0.01)

    buf[2], buf[0] = 0, 0
    kb.send_report(buf)
    sleep(0.01)
    kb.send_report(buf)
    sleep(0.01)
首先定义键盘类kb,然后发送数据,代表按键按下。注意发送数据后需要再次发送0,代表按键释放,否则系统会一直发出按键。例如,下面将发送字母a:

kb_send(4)


因为键盘缓冲区是8字节,第一个字节代表ctrl、shift、alt键状态,2-7字节代表字符,所以一次最多可以发送6个字符,将上面程序略作修改,就可以实现多个字符的发送:

代码: 全选

def kb_sends(c1, c2=0, c3=0, c4=0, c5=0, c6=0, shift=0):
    buf=bytearray(8)
    buf[0] = shift
    buf[2] = c1
    buf[3] = c2
    buf[4] = c3
    buf[5] = c4
    buf[6] = c5
    buf[7] = c6
    kb.send_report(buf)
    sleep(0.01)

    for i in range(8):
        buf = 0

    kb.send_report(buf)
    sleep(0.01)
    kb.send_report(buf)
    sleep(0.01)
例如,使用kb_sends(4,5,6)将发送abc。注意注意USB HID发送的键盘数据并不是字符的ASCII码,而是USB协议定义的数据,具体数据可以参考USB协议中的规定。

鼠标的使用方法和键盘类似,区别在于使用了device[1],数据是4字节,如:

代码: 全选

mouse = usb_hid.devices[1]
mouse.send_report(bytes([0, 100, 0, 0]))
上面的程序,将鼠标位置右移100(x方向)。

缓冲区的数据,第一个代表鼠标按键;第2/3个代表X/Y方向移动距离;第4个字节代表滚动。

USB鼠标键盘演示,当按下触摸键A0时,鼠标做圆圈运动;按下A1,发送数字1;按下A2,发送字母a。

代码: 全选

import usb_hid
from time import sleep
import touchio
from board import *
import math

tp1 = touchio.TouchIn(A0)
tp2 = touchio.TouchIn(A1)
tp3 = touchio.TouchIn(A2)

kb = usb_hid.devices[0]
mouse = usb_hid.devices[1]

n = 0
while 1:
    sleep(0.1)
    if tp1.value:
        t = n*math.pi/360
        x, y = round(10*math.cos(t)), round(10*math.sin(t))
        if x < 0: x += 256
        if y < 0: y += 256
        buf = bytes([0, x, y, 0])
        print(n, buf[0], buf[1] ,buf[2], buf[3])
        mouse.send_report(buf)
        n += 10

    if tp2.value:
        kb.send_report(bytes([0, 0, 0x1E, 0, 0, 0, 0, 0]))
        sleep(0.01)
        kb.send_report(bytes(8))
        kb.send_report(bytes(8))
   
    if tp3.value:
        kb.send_report(bytes([0, 0, 0x04, 0, 0, 0, 0, 0]))
        sleep(0.01)
        kb.send_report(bytes(8))
        kb.send_report(bytes(8))