C# WinForms 使用 CyUSB.dll 访问 USB 设备

1:环境配置

  1. 安装驱动与 SDK
    • 安装 Cypress EZ-USB FX3 SDK(确保包含 CyUSB.dll)
    • 将 CyUSB.dll 添加到项目引用(路径示例:C:\Program Files\Cypress\Cypress USB\Tools\CyUSB\lib\CyUSB.dll
  2. 创建 WinForms 项目
    • 添加 using CyUSB;命名空间

2:核心代码实现

csharp 复制代码
using System;
using System.Windows.Forms;
using CyUSB;

namespace USB_Communication_Demo
{
    public partial class MainForm : Form
    {
        private CyUSBDeviceList usbDeviceList;  // 设备列表
        private CyUSBDevice connectedDevice;    // 当前设备
        private const int TARGET_VID = 0x0483;  // 目标设备VID(替换为实际值)
        private const int TARGET_PID = 0x5750;  // 目标设备PID(替换为实际值)

        public MainForm()
        {
            InitializeComponent();
            InitializeUSB();
        }

        // 初始化USB设备监控
        private void InitializeUSB()
        {
            usbDeviceList = new CyUSBDeviceList(CyConst.DEVICES_ALL);
            usbDeviceList.DeviceAttached += (s, e) => RefreshDeviceList();  // 设备插入事件
            usbDeviceList.DeviceRemoved += (s, e) => RefreshDeviceList();   // 设备拔出事件
            RefreshDeviceList();  // 初始刷新
        }

        // 刷新设备列表(UI更新)
        private void RefreshDeviceList()
        {
            comboBoxDevices.Invoke((MethodInvoker)delegate {
                comboBoxDevices.Items.Clear();
                foreach (CyUSBDevice dev in usbDeviceList)
                {
                    if (dev.VendorID == TARGET_VID && dev.ProductID == TARGET_PID)
                    {
                        comboBoxDevices.Items.Add($"VID:{dev.VendorID:X4} PID:{dev.ProductID:X4}");
                    }
                }
                if (comboBoxDevices.Items.Count > 0) comboBoxDevices.SelectedIndex = 0;
            });
        }

        // 选择设备并连接
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (comboBoxDevices.SelectedIndex >= 0)
            {
                connectedDevice = usbDeviceList[comboBoxDevices.SelectedIndex] as CyUSBDevice;
                if (connectedDevice.Open())
                {
                    lblStatus.Text = "设备已连接";
                    btnSend.Enabled = true;
                }
            }
        }

        // 发送数据(OUT端点)
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (connectedDevice == null) return;

            try
            {
                byte[] data = { 0x01, 0x02, 0x03 };  // 示例数据
                int outEndpoint = 0x01;               // OUT端点号(需根据设备手册调整)
                CyUSBEndPoint endpoint = connectedDevice.EndPointOf(outEndpoint);
                endpoint.XferData(data, data.Length);
                lblLog.AppendText("数据发送成功\n");
            }
            catch (Exception ex)
            {
                lblLog.AppendText($"发送失败: {ex.Message}\n");
            }
        }

        // 接收数据(IN端点)
        private void ReceiveData()
        {
            if (connectedDevice == null) return;

            try
            {
                int inEndpoint = 0x81;                // IN端点号(需根据设备手册调整)
                CyUSBEndPoint endpoint = connectedDevice.EndPointOf(inEndpoint);
                byte[] buffer = new byte[64];         // 缓冲区大小需匹配设备配置
                int bytesRead = endpoint.XferData(ref buffer, ref 64);
                if (bytesRead > 0)
                {
                    string hexData = BitConverter.ToString(buffer, 0, bytesRead);
                    lblLog.AppendText($"接收数据: {hexData}\n");
                }
            }
            catch (Exception ex)
            {
                lblLog.AppendText($"接收失败: {ex.Message}\n");
            }
        }

        // 窗体关闭时释放资源
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            connectedDevice?.Close();
            usbDeviceList.Dispose();
            base.OnFormClosing(e);
        }
    }
}

说明

  1. 设备枚举与热插拔
    • 通过 CyUSBDeviceList实时监控 USB 设备插入/拔出事件
    • 使用 Invoke确保 UI 更新在主线程执行(避免跨线程异常)
  2. 数据传输
    • 发送数据 :通过 EndPointOf获取 OUT 端点,调用 XferData写入数据
    • 接收数据:通过轮询或事件监听(需扩展)读取 IN 端点数据
  3. 资源管理
    • 使用 Dispose()释放 USB 设备列表资源
    • 关闭设备句柄防止资源泄漏

注意

  1. VID/PID 配置
    • 替换 TARGET_VIDTARGET_PID为实际设备的值(可通过设备管理器查看)
  2. 端点号确认
    • 使用工具(如 Cypress Control Center)或设备手册验证 IN/OUT 端点号
  3. 错误处理扩展
    • 添加重试机制(如发送失败时重试 3 次)
    • 检查设备状态:if (connectedDevice.IsOpen)
  4. 数据格式
    • HID 设备需跳过报告 ID(如 buffer.Skip(1).ToArray()

参考示例:在C# Winform中使用CyUSB.dll类库访问usb口的简单示例 www.youwenfan.com/contentcsd/112191.html

扩展功能建议

  • 异步接收数据 :使用 BeginInvoke实现后台接收
  • 协议解析:根据设备协议解析接收到的二进制数据
  • 日志记录:将通信记录保存到文件