[英]Communicating with an USB device over “USB Virtual Serial Port” using C#?
我最近使用普通USB電纜將USB嵌入式設備(mbed lpc1768)插入Windows 7桌面。 根據設備上運行的程序附帶的文檔,它通過USB虛擬串行端口與主機(桌面)通信。
如果需要使用c#讀/寫數據,我從哪里開始? 我可以使用SerialPort .NET類,還是需要使用LibUsbDotNet庫或其他東西?
當我發現USB設備以VCP而不是USB-HID進行通信時,這是個好消息,因為串行連接很容易理解。
如果設備在VCP
(虛擬COM端口)中運行,那么就像使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.