7

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?

Karlth
  • 3,267
  • 2
  • 27
  • 28

1 Answers1

13

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)

Community
  • 1
  • 1
Will Faithfull
  • 1,868
  • 13
  • 20
  • Where do I see the portNo (port name)? SerialPort.GetPortNames returns 0 ports. – Karlth Oct 24 '13 at 00:11
  • In my case, I don't know the port number because it may not always be the same. I use a `ManagementObjectSearcher` to find the device (since I know the name), so I do `var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SERIALPORT")` and iterate over the `ManagementBaseObject` collection in `searcher.Get()`. I'll work it into the answer. – Will Faithfull Oct 24 '13 at 00:19
  • 1
    Well it seems I needed to install a Mbed serial port driver for Windows(http://mbed.org/handbook/Windows-serial-configuration). I ran it and the computer huffed and puffed for a few minutes, finally producing a nice "mbed serial port (COM3)" line in the Device manager! :) I'll try that. – Karlth Oct 24 '13 at 00:23
  • Well if that's the case, for now, you can lazy hard-code the `PortNo` to `"COM3"` – Will Faithfull Oct 24 '13 at 00:24
  • 1
    RtsEnable and DtrEnable were required in my case. +1 – bvj Nov 21 '17 at 05:05
  • Yes, RTS & DTR enable fixed my issue too! – bobwki Feb 25 '21 at 17:07