Python USB通讯

1.下载libusb:

地址:Releases · libusb/libusb · GitHub

下载7z压缩包文件到本地:

解压后将32位版本的dll文件拷贝到C:\Windows\System32,64位的dll文件拷贝到C:\Windows\SysWOW64

2.安装python的usb模块

pip install pyusb

校验安装:

>>> import usb.core
>>> dev = usb.core.find(all=True)

将所有USB设备打印出来。

3.获取USB设备的读写endpoint

device.set_configuration()
    cfg = device.get_active_configuration()
    intf = cfg[(0, 0)]
    usb.util.claim_interface(device, intf)
    # 获取写endpoint
    write_ep = usb.util.find_descriptor(
        intf,
        # match the first OUT endpoint
        custom_match= \
            lambda e: \
                usb.util.endpoint_direction(e.bEndpointAddress) == \
                usb.util.ENDPOINT_OUT
    )
    # 获取读endpoint
    read_ep = usb.util.find_descriptor(
        intf,
        # match the first IN endpoint
        custom_match= \
            lambda e: \
                usb.util.endpoint_direction(e.bEndpointAddress) == \
                usb.util.ENDPOINT_IN
    )

5.通过endpoint读写数据

w_len = write_ep.write(data, timeout)

data = read_ep.read(len, timeout=timeout)

  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
针对 ESP32-S3 的 MicroPython USB 接口通讯编程可以分为两个部分:ESP32-S3 端和 PC 端。 1. ESP32-S3 端 首先,需要在 ESP32-S3 上安装 MicroPython 固件。然后,通过串口连接到 ESP32-S3,打开 REPL 环境。 在 REPL 环境中,可以使用 `uos` 模块的 `stat` 函数检查 USB 设备是否已连接。如果已连接,则可以通过 `uos` 模块的 `mount` 函数将 USB 设备挂载为文件系统。然后,就可以像使用本地文件系统一样在 USB 设备上读写文件了。 下面是示例代码: ```python import uos # 检查 USB 设备是否已连接 if not uos.stat('/dev/usb_stor'): print('USB device not found') else: # 挂载 USB 设备为文件系统 uos.mount('/dev/usb_stor', '/mnt/usb') # 在 USB 设备上创建文件 with open('/mnt/usb/test.txt', 'w') as f: f.write('Hello, USB!') # 从 USB 设备上读取文件 with open('/mnt/usb/test.txt', 'r') as f: print(f.read()) # 卸载 USB 设备 uos.umount('/mnt/usb') ``` 2. PC 端 在 PC 端,可以使用 Python 的 `serial` 模块连接到 ESP32-S3 的串口。然后,通过串口发送命令和数据,与 ESP32-S3 进行通讯。 下面是示例代码: ```python import serial # 打开串口连接 ser = serial.Serial('/dev/ttyUSB0', 115200) # 发送命令 ser.write(b'hello') # 接收数据 data = ser.read(10) print(data) # 关闭串口连接 ser.close() ``` 需要注意的是,ESP32-S3 与 PC 端的串口通讯需要使用相同的波特率和数据格式等参数。在示例代码中,波特率为 115200,数据格式为 8 个数据位,无校验位,1 个停止位。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值