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

无人久伴 提交于 2019-12-03 03:20:41
Will Faithfull

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!