Working with USB devices in .NET

前端 未结 12 1220
暖寄归人
暖寄归人 2020-11-27 10:56

Using .Net (C#), how can you work with USB devices?

How can you detect USB events (connections/disconnections) and how do you communicate with devices (read/write).

12条回答
  •  没有蜡笔的小新
    2020-11-27 11:20

    If you have National Instruments software on you PC you can create a USB Driver using their "NI-VISA Driver Wizard".

    Steps to create the USB Driver: http://www.ni.com/tutorial/4478/en/

    Once you created the driver you will be able to Write and Read bytes to any USB Device.

    Make sure the driver is seen by windows under Device Manager:

    enter image description here

    C# Code:

        using NationalInstruments.VisaNS;
    
        #region UsbRaw
        /// 
        /// Class to communicate with USB Devices using the UsbRaw Class of National Instruments
        /// 
        public class UsbRaw
        {
            private NationalInstruments.VisaNS.UsbRaw usbRaw;
            private List DataReceived = new List();
    
            /// 
            /// Initialize the USB Device to interact with
            /// 
            /// 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.
            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);
            }
    
            /// 
            /// Clears a USB Device from any previous commands
            /// 
            public void Clear()
            {
                usbRaw.Clear();
            }
    
            /// 
            /// Writes Bytes to the USB Device
            /// 
            /// 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)
            /// Data to send to the USB device
            public void Write(short EndPoint, byte[] BytesToSend)
            {
                usbRaw.BulkOutPipe = EndPoint;
                usbRaw.Write(BytesToSend);       // Write to USB
            }
    
            /// 
            /// Reads bytes from a USB Device
            /// 
            /// Bytes Read
            public byte[] Read()
            {
                usbRaw.ReadByteArray();     // This fires the UsbRawInterruptEventHandler                
    
                byte[] rxBytes = DataReceived.ToArray();      // Collects the data received
    
                return rxBytes;
            }
    
            /// 
            /// This is used to get the data received by the USB device
            /// 
            /// 
            /// 
            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));
                }
            }
    
            /// 
            /// Use this function to clean up the UsbRaw class
            /// 
            public void Dispose()
            {
                usbRaw.DisableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler);
    
                if (usbRaw != null)
                {
                    usbRaw.Dispose();
                }              
            }
    
        }
        #endregion UsbRaw
    

    Usage:

    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();
    

    Hope this helps someone.

提交回复
热议问题