我最近使用普通USB电缆将USBembedded式设备(mbed lpc1768)插入Windows 7桌面。 根据设备上运行的程序附带的文档,它通过USB虚拟串行端口与主机(桌面)进行通信。
从哪里开始,如果我需要读/写数据使用C#? 我可以使用SerialPort .NET类吗?还是我需要使用LibUsbDotNet库或者其他的东西?
当我发现USB设备以VCP而不是USB-HID进行通信时,这是个好消息,因为串行连接很容易理解。
如果设备在VCP
(Virtual Com Port)中运行,那么就像使用System.IO.Ports.SerialPort
类型一样简单。 您将需要了解有关设备的一些基本信息,其中大部分信息可以从Windows Management(设备管理器)收集。 像这样构建之后:
SerialPort port = new SerialPort(portNo, baudRate, parity, dataBits, stopBits);
您可能需要也可能不需要设置其他标志,如请求发送 (RTS)和数据终端就绪 (DTR)
port.RtsEnable = true; port.DtrEnable = true;
然后,打开端口。
port.Open();
要监听,可以将一个事件处理程序附加到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 };
要发送,你可以使用port.Write(byte[] buffer, int offset, int count)