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

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口的简单示例 www.youwenfan.com/contentcsd/112191.html

扩展功能建议

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

相关文章:

  • 第6.4节:awk语言 for 语句
  • Java ThreadLocal为什么要用弱引用
  • 2025最新:Salesforce认证考试—考试中心预约全流程
  • 香港电讯为知名投资公司搭建高效、安全IT管理服务体系
  • GraphRAG 知识图谱核心升级:集成 langextract 与 Gemini ----实现高精度实体与关系抽取
  • 营业执照识别技术应用OCR与深度学习,实现高效、精准提取企业核心信息,推动数字化管理发展。
  • Linux时间处理函数
  • 机器学习(三)sklearn机器学习
  • 第二阶段WinForm-11:自定义控件
  • Java全栈工程师的面试实战:从技术细节到业务场景
  • 在八月点燃AI智慧之火:CSDN创作之星挑战赛开启灵感盛宴
  • 04.《VLAN基础与配置实践指南》
  • Django Admin 管理工具
  • NSSCTF-[NISACTF 2022]string_WP
  • 身份证实名认证API集成—身份核验接口-网络平台安全合规
  • mitmproxy的使用初试
  • windows中Qwen3‑Coder 与 Claude Code 搭配使用
  • 《UE5_C++多人TPS完整教程》学习笔记45 ——《P46 待机与跳跃动画(Idle And Jumps)》
  • 【完整源码+数据集+部署教程】植物病害检测系统源码和数据集:改进yolo11-EMSCP
  • Lombok vs Java Record:谁才是未来?
  • week5-[二维数组]翻转
  • Node.js 的流(Stream)是什么?有哪些类型?
  • DBeaver 的 PostgreSQL 驱动包默认存储位置
  • 计算机网络知识--对称加密、非对称加密和数字证书详解
  • “上门做饭”平台的核心技术栈与运营壁垒是什么?
  • OpenCV之霍夫变换
  • Linux系统部署:Certbot 实现 Nginx 自动续期部署 Let‘s Encrypt 免费 SSL 证书
  • css三角形
  • 万字解析RAG(检索增强生成)系统的构建与优化,从基础架构逐步深入到高级技术
  • 深度学习入门Day10:深度强化学习原理与实战全解析