[英]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. 我最近使用普通USB电缆将USB嵌入式设备(mbed lpc1768)插入Windows 7桌面。 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.
根据设备上运行的程序附带的文档,它通过USB虚拟串行端口与主机(桌面)通信。
Where do I start if I need to read/write data using c#? 如果需要使用c#读/写数据,我从哪里开始? Could I use the SerialPort .NET class or do I need to use the LibUsbDotNet library or perhaps something else?
我可以使用SerialPort .NET类,还是需要使用LibUsbDotNet库或其他东西?
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. 当我发现USB设备以VCP而不是USB-HID进行通信时,这是个好消息,因为串行连接很容易理解。
If the device is operating in VCP
(Virtual Com Port), then it is as easy as using the System.IO.Ports.SerialPort
type. 如果设备在
VCP
(虚拟COM端口)中运行,那么就像使用System.IO.Ports.SerialPort
类型一样简单。 You will need to know some basic information about the device, most of which can be gleaned from Windows Management (Device Manager). 您需要了解有关该设备的一些基本信息,其中大部分信息可以从Windows Management(设备管理器)中收集。 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) 您可能需要或可能不需要设置一些额外的标志,例如请求发送 (RTS)和数据终端就绪 (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
,然后使用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)
要发送,可以使用
port.Write(byte[] buffer, int offset, int count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.