rp2040/example/peripherals/usb/usb_device/myusb.py

75 lines
2.1 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import usb.core
import usb.util
# USB设备参数
VENDOR_ID = 0x0000 # 替换为实际的VID
PRODUCT_ID = 0x0001 # 替换为实际的PID
OUT_ENDPOINT = 0x01 # EP1 OUT端点
IN_ENDPOINT = 0x82 # EP2 IN端点 (注意: IN端点通常最高位设为1)
MAX_FIFO_SIZE = 64 # 最大FIFO长度
def find_usb_device():
"""查找并返回指定的USB设备"""
dev = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
if dev is None:
raise ValueError("设备未找到请检查连接或VID/PID")
return dev
def configure_device(dev):
"""配置USB设备"""
# 如果是Linux可能需要先detach内核驱动
# if dev.is_kernel_driver_active(0):
# dev.detach_kernel_driver(0)
# 设置配置
dev.set_configuration()
# 获取配置
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
print("设备配置成功")
return dev
def send_data(dev, data):
"""向OUT端点发送数据"""
if len(data) > MAX_FIFO_SIZE:
raise ValueError(f"数据长度超过最大FIFO大小({MAX_FIFO_SIZE}字节)")
# 发送数据到EP1 OUT
bytes_written = dev.write(OUT_ENDPOINT, data)
print(f"发送成功: {bytes_written} 字节")
return bytes_written
def receive_data(dev, max_length=MAX_FIFO_SIZE):
"""从IN端点接收数据"""
# 从EP2 IN读取数据
data = dev.read(IN_ENDPOINT, max_length)
print(f"接收成功: {len(data)} 字节")
return data
def main():
try:
# 查找并配置设备
dev = find_usb_device()
dev = configure_device(dev)
# 示例数据发送
test_data = b"Hello USB Device!" # 测试数据
send_data(dev, test_data)
# 示例数据接收
received_data = receive_data(dev)
print("接收到的数据:", received_data)
except usb.core.USBError as e:
print(f"USB错误: {e}")
except Exception as e:
print(f"错误: {e}")
finally:
# 释放设备
usb.util.dispose_resources(dev)
if __name__ == "__main__":
main()