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

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 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示