2016-04-29 28 views
0

我想不斷讀取串行端口,並在我的Windows 10通用應用程序(C#)的文本框中獲得輸出。我發現從MS系列樣品此代碼https://github.com/ms-iot/samples/tree/develop/SerialSample/CS我怎樣才能不斷讀取在Windows 10通用(C#)的串行端口

private async void Listen() 
    { 
     try 
     { 
      if (serialPort != null) 
      { 
       dataReaderObject = new DataReader(serialPort.InputStream); 

       while (true) 
       { 
        await ReadAsync(ReadCancellationTokenSource.Token); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      if (ex.GetType().Name == "TaskCanceledException") 
      { 
       CloseDevice(); 
      } 
     } 
     finally 
     { 
      if (dataReaderObject != null) 
      { 
       dataReaderObject.DetachStream(); 
       dataReaderObject = null; 
      } 
     } 
    } 

    private async Task ReadAsync(CancellationToken cancellationToken) 
    { 
     Task<UInt32> loadAsyncTask; 

     uint ReadBufferLength = 1024; 

     cancellationToken.ThrowIfCancellationRequested(); 

     dataReaderObject.InputStreamOptions = InputStreamOptions.Partial; 

     loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken); 

     UInt32 bytesRead = await loadAsyncTask; 
     if (bytesRead > 0) 
     { 
      reciveTextBox.Text = dataReaderObject.ReadString(bytesRead); 
     } 
    } 

但是當我打電話聽()函數與點擊一個按鈕,有時它有時讀端口沒有。

請給出一個解決方案,它會不斷讀取串行端口並在文本框中輸出結果。

MainPage.xaml.cs中的全部代碼是在這裏:http://pastebin.com/dmsTUBmT

回答

2

我在GitHub上的例子:Arduino_UWP_App

如果在短期內形容。 以下是主要變量:

private SerialDevice serialPort = null; 
DataReader dataReaderObject = null; 

不要忘記參考:

using Windows.Devices.SerialCommunication; 
using Windows.Devices.Enumeration; 
using Windows.Storage.Streams; 

首先,你應該找到設備

string qFilter = SerialDevice.GetDeviceSelector("COM3"); 
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter); 

     if (devices.Any()) 
     { 
      string deviceId = devices.First().Id; 
      await OpenPort(deviceId); 
     } 

的方式是這樣,你可以打開端口:

private async Task OpenPort(string deviceId) 
    { 
     serialPort = await SerialDevice.FromIdAsync(deviceId); 
     if (serialPort != null) 
     { 
      serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000); 
      serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000); 
      serialPort.BaudRate = 9600; 
      serialPort.Parity = SerialParity.None; 
      serialPort.StopBits = SerialStopBitCount.One; 
      serialPort.DataBits = 8; 
      serialPort.Handshake = SerialHandshake.None; 
     } 
    } 

現在你可以監聽消息:

while (true) 
     { 
      await Listen(); 
     } 

.......

private async Task Listen() 
    { 
      if (serialPort != null) 
      { 
       dataReaderObject = new DataReader(serialPort.InputStream); 
       await ReadAsync(ReadCancellationTokenSource.Token); 
      }   
    } 

.......

private async Task ReadAsync(CancellationToken cancellationToken) 
    { 
     Task<UInt32> loadAsyncTask; 

     uint ReadBufferLength = 256; // only when this buffer would be full next code would be executed 
     dataReaderObject.InputStreamOptions = InputStreamOptions.Partial; 
     loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken); // Create a task object 

     UInt32 bytesRead = await loadAsyncTask; // Launch the task and wait until buffer would be full 

     if (bytesRead > 0) 
     { 
      string strFromPort = dataReaderObject.ReadString(bytesRead); 
     } 
    } 
+0

儘管此鏈接可能回答問題,但最好在此處包含答案的基本部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – Marusyk

0

看來,通過操縱讀取超時時間可以收到不同的響應。數字越小(毫秒),讀取速度越高,讀取的字節越接近或等於BytesAvailable。

數字越高,響應越慢並具有更完整的讀取緩衝區(可能包含來自源設備的多個響應)。

原始SerialSample代碼會顯示此內容,如果修改爲在循環中執行預定義的定時寫操作,那麼可以看到以不同方式讀取每個超時值的預期響應。那些對PLC設備進行實驗的人可能會很容易地知道這一點,知道對特定PLC有何期望的響應。

+0

老實說,我不明白這可能與這個問題有關,「有時它讀端口有時它不。」 –