当前位置: 首页 > news >正文

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

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:核心代码实现

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口的简单示例

扩展功能建议

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

相关文章:

  • MarkDown学习
  • MySql EXPLAIN 详解
  • Transformer完整实现及注释
  • GAS_Aura-Granting Abilities
  • 第10章 STM32 模拟SPI电阻屏触摸配置和测试
  • ABAP同步和异步
  • 扩展 Min-Max 容斥
  • 北京市推进中小学人工智能教育工作方案(2025—2027年)
  • IvorySQL 适配 LoongArch 龙架构
  • ICPC模拟赛#1
  • 从基础到实战:一文吃透 JS Tuples 与 Records 的所有核心用法
  • [题解] P13777 「o.OI R2」Meowalkane
  • C++14之exchange
  • Blazor之第三方登录
  • 深入解析:物联网时序数据库IoTDB是什么?
  • Python-httpx库的post请求的几种参数的区别
  • 精准把控人力,PJMan “负荷分析” 助力项目高效推进
  • 车载电动充气泵芯片方案设计
  • [题解]P4281 [AHOI2008] 紧急集合 / 聚会
  • 【API接口】最新可用红果短剧接口
  • 数据结构与算法-28.图
  • 加入任务计划
  • qoj2607 Survey
  • 移远EC800M RTOS笔记
  • Linux 实例:配置 NTP 服务
  • 开发过程中常见的设计模式
  • 论Intel CPU 进化史:德承工控机全面进化 搭载新一代 Intel Core™ Ultra 7/5/3 处理器 - Johnny
  • mysql绿色版,无需安装的快速数据库解决方案
  • MyEMS:功能强大的开源能源管理系统,助力企业实现精细化能效管理
  • mysql 导入sql,从入门到精通