在.NET中使用USB设备

使用.Net(C#),你如何使用USB设备?

如何检测USB事件(连接/断开连接),以及如何与设备进行通信(读/写)。

有没有一个原生的.net解决scheme来做到这一点?

没有原生的 (如系统库)解决scheme。 这就是为什么SharpUSBLib存在如moobaa所提到的。

如果您希望为USB设备推出自己的处理程序,则可以查看System.IO.Ports的SerialPort类 。

我试过使用SharpUSBLib,它搞砸了我的电脑(需要一个系统还原)。 发生在同一个项目上的同事也。

我在LibUSBDotNet中find了一个替代方法: http : //sourceforge.net/projects/libusbdotnet虽然还没有使用它,但看起来很好,最近更新了(不像夏普)。

编辑:截至2017年2月中旬,LibUSBDotNet已于2周前更新。 同时SharpUSBLib自2004年以来一直没有更新。

.NET的#usblib USB库

我使用下面的代码来检测USB设备插入和拔出从我的电脑时:

class USBControl : IDisposable { // used for monitoring plugging and unplugging of USB devices. private ManagementEventWatcher watcherAttach; private ManagementEventWatcher watcherRemove; public USBControl() { // Add USB plugged event watching watcherAttach = new ManagementEventWatcher(); //var queryAttach = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); watcherAttach.Start(); // Add USB unplugged event watching watcherRemove = new ManagementEventWatcher(); //var queryRemove = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3"); watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved); watcherRemove.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3"); watcherRemove.Start(); } /// <summary> /// Used to dispose of the USB device watchers when the USBControl class is disposed of. /// </summary> public void Dispose() { watcherAttach.Stop(); watcherRemove.Stop(); //Thread.Sleep(1000); watcherAttach.Dispose(); watcherRemove.Dispose(); //Thread.Sleep(1000); } void watcher_EventArrived(object sender, EventArrivedEventArgs e) { Debug.WriteLine("watcher_EventArrived"); } void watcher_EventRemoved(object sender, EventArrivedEventArgs e) { Debug.WriteLine("watcher_EventRemoved"); } ~USBControl() { this.Dispose(); } } 

您必须确保在closures应用程序时调用Dispose()方法。 否则,在closures时,您将在运行时收到COM对象错误。

我build议LibUSBDotNet ,我已经使用了2年的图书馆。 如果您必须使用USB设备(发送请求,处理响应),则该库是我能find的最佳解决scheme。

优点:

  • 具有您需要以同步或asynchronous模式工作的所有方法。
  • 提供的源代码
  • 足够的样本立即开始使用它。

缺点:

  • 糟糕的文档(这是开源项目的常见问题)。 基本上,你可以在CHM帮助文件中find对方法的常见描述,就是这样。 但是我仍然发现提供的样本和源代码足够用于编码。 有时我会看到一个奇怪的行为,想知道为什么这样做,甚至不能提示…
  • 似乎不再支持。 最新版本于2010年10月发布。有时候很难得到答案。

有一个关于让SharpUSBLib库和HID驱动程序在C#下工作的教程:

http://www.developerfusion.com/article/84338/making-usb-c-friendly/

有一个通用工具包WinDriver,用于编写支持#.NET的用户模式的USB驱动程序

如果您在PC上安装了National Instruments软件,则可以使用其“NI-VISA驱动程序向导”创buildUSB驱动程序

创buildUSB驱动程序的步骤: http : //www.ni.com/tutorial/4478/en/

一旦你创build了驱动程序,你将能够写入和读取字节到任何USB设备。

确保设备pipe理器下的窗口能看到驱动程序:

在这里输入图像描述

C#代码:

  using NationalInstruments.VisaNS; #region UsbRaw /// <summary> /// Class to communicate with USB Devices using the UsbRaw Class of National Instruments /// </summary> public class UsbRaw { private NationalInstruments.VisaNS.UsbRaw usbRaw; private List<byte> DataReceived = new List<byte>(); /// <summary> /// Initialize the USB Device to interact with /// </summary> /// <param name="ResourseName">In this format: "USB0::0x1448::0x8CA0::NI-VISA-30004::RAW". Use the NI-VISA Driver Wizard from Start»All Programs»National Instruments»VISA»Driver Wizard to create the USB Driver for the device you need to talk to.</param> public UsbRaw(string ResourseName) { usbRaw = new NationalInstruments.VisaNS.UsbRaw(ResourseName, AccessModes.NoLock, 10000, false); usbRaw.UsbInterrupt += new UsbRawInterruptEventHandler(OnUSBInterrupt); usbRaw.EnableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler); } /// <summary> /// Clears a USB Device from any previous commands /// </summary> public void Clear() { usbRaw.Clear(); } /// <summary> /// Writes Bytes to the USB Device /// </summary> /// <param name="EndPoint">USB Bulk Out Pipe attribute to send the data to. For example: If you see on the Bus Hound sniffer tool that data is coming out from something like 28.4 (Device column), this means that the USB is using Endpoint 4 (Number after the dot)</param> /// <param name="BytesToSend">Data to send to the USB device</param> public void Write(short EndPoint, byte[] BytesToSend) { usbRaw.BulkOutPipe = EndPoint; usbRaw.Write(BytesToSend); // Write to USB } /// <summary> /// Reads bytes from a USB Device /// </summary> /// <returns>Bytes Read</returns> public byte[] Read() { usbRaw.ReadByteArray(); // This fires the UsbRawInterruptEventHandler byte[] rxBytes = DataReceived.ToArray(); // Collects the data received return rxBytes; } /// <summary> /// This is used to get the data received by the USB device /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnUSBInterrupt(object sender, UsbRawInterruptEventArgs e) { try { DataReceived.Clear(); // Clear previous data received DataReceived.AddRange(e.DataBuffer); } catch (Exception exp) { string errorMsg = "Error: " + exp.Message; DataReceived.AddRange(ASCIIEncoding.ASCII.GetBytes(errorMsg)); } } /// <summary> /// Use this function to clean up the UsbRaw class /// </summary> public void Dispose() { usbRaw.DisableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler); if (usbRaw != null) { usbRaw.Dispose(); } } } #endregion UsbRaw 

用法:

 UsbRaw usbRaw = new UsbRaw("USB0::0x1448::0x8CA0::NI-VISA-30004::RAW"); byte[] sendData = new byte[] { 0x53, 0x4c, 0x56 }; usbRaw.Write(4, sendData); // Write bytes to the USB Device byte[] readData = usbRaw.Read(); // Read bytes from the USB Device usbRaw.Dispose(); 

希望这有助于某人。

大多数USB芯片组都附带驱动程序。 Silicon Labs有一个。

使用这篇文章 ,我已经得到了一个很好的Teensy的接口