Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicating with an USB device over “USB Virtual Serial Port” using C#?

I recently plugged in an USB embedded device(mbed lpc1768) using a normal USB cable to a Windows 7 desktop. According to the docs that came with the program running on the device it communicates with the host(desktop) over a USB Virtual Serial Port.

Where do I start if I need to read/write data using c#? Could I use the SerialPort .NET class or do I need to use the LibUsbDotNet library or perhaps something else?

like image 215
Karlth Avatar asked Oct 23 '13 23:10

Karlth


People also ask

What is USB virtual serial port?

A USB Virtual COM Port allows you to use a USB Interface to talk to serial devices. This essentially gives users a simple pathway to communicating to peripherals using software development tools that support serial communications, a relatively common standard is most programming languages.

Can I use COM port for USB?

Since USB can do the same thing as many COM ports, most computers now lack serial ports. If you need one to satisfy your software, though, USB's benefits don't help you. The solution is to plug a USB to serial adapter into a USB port and set it to act as COM1.


1 Answers

It is excellent news when I find out that a USB device communicates in VCP rather than USB-HID, because serial connections are easy to understand.

If the device is operating in VCP (Virtual Com Port), then it is as easy as using the System.IO.Ports.SerialPort type. You will need to know some basic information about the device, most of which can be gleaned from Windows Management (Device Manager). After constructing like so:

SerialPort port = new SerialPort(portNo, baudRate, parity, dataBits, stopBits);

You may or may not need to set some additional flags, such as Request to send (RTS) and Data Terminal Ready (DTR)

port.RtsEnable = true;
port.DtrEnable = true;

Then, open the port.

port.Open();

To listen, you can attach an event handler to port.DataReceived and then use port.Read(byte[] buffer, int offset, int count)

port.DataReceived += (sender, e) => 
{ 
    byte[] buffer = new byte[port.BytesToRead];
    port.Read(buffer,0,port.BytesToRead);
    // Do something with buffer
};

To send, you can use port.Write(byte[] buffer, int offset, int count)

like image 76
Will Faithfull Avatar answered Oct 27 '22 01:10

Will Faithfull