2013-10-23 195 views
7

我最近使用普通的USB電纜將USB嵌入式設備(mbed lpc1768)插入Windows 7桌面。根據設備上運行的程序附帶的文檔,它通過USB虛擬串行端口與主機(桌面)進行通信。使用C#通過「USB虛擬串行端口」與USB設備通信?

如果我需要使用c#讀取/寫入數據,我該從哪裏開始?我可以使用SerialPort .NET類嗎?還是需要使用LibUsbDotNet庫或其他可能?

回答

10

當我發現USB設備使用VCP而不是USB-HID進行通信時,這是個好消息,因爲串行連接很容易理解。

如果設備在VCP(虛擬Com端口)中運行,則與使用System.IO.Ports.SerialPort類型一樣簡單。您需要了解有關設備的一些基本信息,其中大部分可以從Windows Management(設備管理器)收集。建設像這樣經過:

SerialPort port = new SerialPort(portNo, baudRate, parity, dataBits, stopBits); 

may or may not需要設置一些附加的標誌,如請求發送(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)

+0

我在哪裏看到PORTNO(端口名稱)? SerialPort.GetPortNames返回0端口。 – Karlth

+0

就我而言,我不知道端口號,因爲它可能並不總是相同的。我使用'ManagementObjectSearcher'來查找設備(因爲我知道名稱),因此我執行'var searcher = new ManagementObjectSearcher(「SELECT * FROM WIN32_SERIALPORT」)'並遍歷'searcher.Get中的'ManagementBaseObject'集合)'。我會把它寫入答案。 –

+1

好吧,我似乎需要爲Windows安裝Mbed串行端口驅動程序(http://mbed.org/handbook/Windows-serial-configuration)。我運行它,計算機充氣膨脹幾分鐘,最後在設備管理器中生成一個很好的「mbed串行端口(COM3)」行! :)我會嘗試。 – Karlth