代码: 全选
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_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)
鼠标的使用方法和键盘类似,区别在于使用了device[1],数据是4字节,如:
代码: 全选
mouse = usb_hid.devices[1]
mouse.send_report(bytes([0, 100, 0, 0]))
缓冲区的数据,第一个代表鼠标按键;第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))