weixin_53582602 2022-01-05 14:17 采纳率: 52.4%
浏览 193
已结题

python 向 板卡通过 usb hid 发送数据

目前需求想通过 usb hid 传输hex文件,第一步先转化成bin文件,根据hid协议通过64 组数据一位进行传输,以下是源码

import usb.core
import usb.util
from intelhex import IntelHex

def hex_to_bin(hex_path, bin_path):
    # load hex file
    ih = IntelHex(hex_path)
    # hex to bin file
    ih.tobinfile(bin_path)

if __name__ == '__main__':
    
    # usb vid and pid
    vid = 0xC251
    pid = 0x1A01
    
    # file name
    hex_name = 'HID_Demo_20211227.hex'
    bin_name = 'HID_Demo_20211227.bin'
    
    # find our device
    dev = usb.core.find(idVendor = vid, idProduct = pid)
    
    # was it found?
    if dev is None:
        raise ValueError('Device not found')
    
    # set the active configuration. With no arguments, the first
    # configuration will be the active one
    dev.set_configuration()
    
    # get an endpoint instance
    cfg = dev.get_active_configuration()
    intf = cfg[(0,0)]
    
    ep_in = usb.util.find_descriptor(
        intf,
        # match the first IN endpoint
        custom_match = \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_IN)
    
    assert ep_in is not None
    
    ep_out = usb.util.find_descriptor(
        intf,
        # match the first OUT endpoint
        custom_match = \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_OUT)
    
    assert ep_out is not None
    
    # hex to bin file
    hex_to_bin(hex_name, bin_name)
    
    # open bin file
    file = open(bin_name, "rb")
    #demo = open('demo.bin', 'ab+')
    while True:
        data = file.read(64)
        if data == b"":
            break
        #demo.write(data)
        ep_out.write(data)
        #print(data)
    file.close()
    #demo.close()

但是通过bus hound 抓取输出发现

img

多发送了一条前面+了一条加了00的 65 组数据,请问是什么原因,求解答,谢谢。

  • 写回答

1条回答 默认 最新

  • qllaoda 2022-01-06 10:16
    关注

    我以前做HID设备的时候也发现这个现象,但是单片机那边收到的是正常的,所以就不要管了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月15日
  • 已采纳回答 1月7日
  • 创建了问题 1月5日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵