C# USB通讯

关注+星标公众,及时获取更多技术分享~ 

 作者 | 冰茶奥利奥

微信公众号 | 嵌入式电子创客街

项目工程文件下载: 工程文件下载地址
看了很多网上的博客,讲述如何用C#进行USB设备操作,很多都是不对的。以至于南辕北辙。我们可以使用usb库。在c下有usblib库,在C#下该如何使用libusb呢,下面介绍C#下的强大的开源USB类库就登场了:LibUSBDotNet,没错就是.NET下的libusb,这也是个开源项目,已经把libusb封装成了一个完整的类库它是sourceforge上的一个开源项目,下载WIN下的EXE安装即可,里面包含了很多的范例,还有说明文档(CHM格式的,超级方便的)。下面简单介绍一下该如何使用LibUSBDotNet。

1、首先你需要创建一个C#的应用程序(控制台、窗体都可以)

2、将LibUsbDotNet安装目录下Src目录下LibWinUsb拷贝一份到你的工程根目录下

3、不需要多说了吧,在你的解决方案上右击,添加现有项目,将LibWinUsb目录下的项目包含进来

4、在你的项目上右击,添加引用,选择LibUSBDotNet项目,如下图:

下面提供一个读取数据的范例:笔者插上了一个U盘,用bushound检查到该U盘的VID和PID:

然而,单纯这样是不够的,我们还需要用到usblib的工具,注册这个设备才能使用。libusb-win32 filter这个工具,只有在这个工具里面选择过的设备,才能是用libusbdotnet的库函数打开。

那么VID是0x0930,PID是0x6544.填入函数中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LibUsbDotNet;
using LibUsbDotNet.Main;
using LibUsbDotNet.Info;
using LibUsbDotNet.Descriptors;
using LibUsbDotNet.LibUsb;
using LibUsbDotNet.WinUsb;
namespace USBTest
{
    internal class Program
    {
        public static UsbDevice MyUsbDevice;


        #region SET YOUR USB Vendor and Product ID!  


        public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x930,0x6544);//U盘ID,可以通过Bushound读出来


        #endregion


        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;


            try
            {
                // Find and open the usb device.  
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);


                // If the device is open and ready  
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");


                // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)  
                // it exposes an IUsbDevice interface. If not (WinUSB) the   
                // 'wholeUsbDevice' variable will be null indicating this is   
                // an interface of a device; it does not require or support   
                // configuration and interface selection.  
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,   
                    // the desired configuration and interface must be selected.  


                    // Select config #1  
                    wholeUsbDevice.SetConfiguration(1);


                    // Claim interface #0.  
                    wholeUsbDevice.ClaimInterface(0);
                }


                // open read endpoint 1.  
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);




                byte[] readBuffer = new byte[1024];
                while (ec == ErrorCode.None)
                {
                    int bytesRead;


                    // If the device hasn't sent data in the last 5 seconds,  
                    // a timeout error (ec = IoTimedOut) will occur.   
                    ec = reader.Read(readBuffer, 5000, out bytesRead);


                    if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
                    Console.WriteLine("{0} bytes read", bytesRead);


                    // Write that output to the console.  
                    Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                }


                Console.WriteLine("\r\nDone!\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)  
                        // it exposes an IUsbDevice interface. If not (WinUSB) the   
                        // 'wholeUsbDevice' variable will be null indicating this is   
                        // an interface of a device; it does not require or support   
                        // configuration and interface selection.  
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.  
                            wholeUsbDevice.ReleaseInterface(0);
                        }


                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;


                    // Free usb resources  
                    UsbDevice.Exit();


                }


                // Wait for user input..  
                Console.ReadKey();
            }
        }
    }
}

项目工程文件下载:工程文件下载地址

如果您觉得这篇文章帮到了你,请点赞或者留下您的评论,您的鼓励是我前进的动力~

关注博主公众号 “嵌入式电子创客街” 获取更多及时技术分享~

  • 23
    点赞
  • 132
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值