使用 C# 通过“USB 虚拟串行端口”与 USB 设备通信?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19554229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Communicating with an USB device over “USB Virtual Serial Port” using C#?
提问by Karlth
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.
我最近使用普通 USB 电缆将 USB 嵌入式设备(mbed lpc1768)插入到 Windows 7 桌面。根据设备上运行的程序随附的文档,它通过 USB 虚拟串行端口与主机(桌面)进行通信。
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?
如果我需要使用 c# 读/写数据,我从哪里开始?我可以使用 SerialPort .NET 类还是需要使用 LibUsbDotNet 库或其他东西?
采纳答案by 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.
当我发现 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. 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:
如果设备在VCP
(Virtual Com Port) 中运行,那么它就像使用System.IO.Ports.SerialPort
类型一样简单。您需要了解有关设备的一些基本信息,其中大部分信息可以从 Windows 管理(设备管理器)中收集。像这样构建后:
SerialPort port = new SerialPort(portNo, baudRate, parity, dataBits, stopBits);
You may or may notneed 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();
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)