使用 C# 通过“USB 虚拟串行端口"与 USB 设备通信? [英] Communicating with an USB device over “USB Virtual Serial Port” using C#?

查看:142
本文介绍了使用 C# 通过“USB 虚拟串行端口"与 USB 设备通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近使用普通 USB 电缆将 USB 嵌入式设备 (mbed lpc1768) 插入到 Windows 7 桌面.根据设备上运行的程序随附的文档,它通过 USB 虚拟串行端口与主机(桌面)通信.

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.

如果我需要使用 c# 读/写数据,我从哪里开始?我可以使用 SerialPort .NET 类还是需要使用 LibUsbDotNet 库或其他东西?

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?

推荐答案

当我发现 USB 设备使用 VCP 而不是 USB-HID 进行通信时,这是个好消息,因为串行连接很容易理解.

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.

如果设备在 VCP(虚拟 Com 端口)下运行,那么它就像使用 System.IO.Ports.SerialPort 类型一样简单.您需要了解有关设备的一些基本信息,其中大部分信息可以从 Windows 管理(设备管理器)中收集.像这样构建后:

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);

可能会也可能不会 需要设置一些额外的标志,例如Request to send (RTS) 和Data Terminal Ready (DTR)

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;

然后,打开端口.

port.Open();

要监听,您可以将事件处理程序附加到 port.DataReceived,然后使用 port.Read(byte[] buffer, int offset, int count)>

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
};

发送,可以使用port.Write(byte[] buffer, int offset, int count)

这篇关于使用 C# 通过“USB 虚拟串行端口"与 USB 设备通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆