簡體   English   中英

如何使用通用Windows應用程序將串行數據寫入COM端口?

[英]How to write serial data to COM ports with Universal Windows Application?

通常,C#應用程序使用System.IO.Ports如下所示:

SerialPort port = new SerialPort("COM1"); 
port.Open(); 
port.WriteLine("test");`

但Universal Windows Applications不支持System.IO.Ports因此無法使用此方法。 有誰知道如何通過UWA中的COM端口寫入串行數據?

您可以使用Windows.Devices.SerialCommunicationWindows.Storage.Streams.DataWriter類執行此操作:

這些類提供了發現此類串行設備, 讀取和寫入數據以及控制流控制的特定於串行的屬性的功能,例如設置波特率,信號狀態。

通過向Package.appxmanifest添加以下功能:

<Capabilities>
  <DeviceCapability Name="serialcommunication">
    <Device Id="any">
      <Function Type="name:serialPort" />
    </Device>
  </DeviceCapability>
</Capabilities>

然后運行以下代碼:

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

//...   

string selector = SerialDevice.GetDeviceSelector("COM3"); 
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
if(devices.Count > 0)
{
    DeviceInformation deviceInfo = devices[0];
    SerialDevice serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);
    serialDevice.BaudRate = 9600;
    serialDevice.DataBits = 8;
    serialDevice.StopBits = SerialStopBitCount.Two;
    serialDevice.Parity = SerialParity.None;

    DataWriter dataWriter = new DataWriter(serialDevice.OutputStream);
    dataWriter.WriteString("your message here");
    await dataWriter.StoreAsync();
    dataWriter.DetachStream();
    dataWriter = null;
}
else
{
    MessageDialog popup = new MessageDialog("Sorry, no device found.");
    await popup.ShowAsync();
}

Microsoft提供了一個在通用Windows應用程序中使用SerialDevice類訪問和使用com端口的示例,名為CustomSerialDeviceAccess。

微軟已將其發布在GitHub上。 你可以在這里找到它:

https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/CustomSerialDeviceAccess

微軟說這個示例應用程序:

“此示例允許用戶配置串行設備並與之通信。您可以選擇以下四種方案之一:

使用設備選擇列表連接/斷開連接; 配置串口設備; 與串口設備通信; 在串行設備上注冊事件“

參考文獻:Microsoft,GitHub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM