繁体   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