如何使用通用 Windows 应用程序将串行数据写入 COM 端口? [英] How to write serial data to COM ports with Universal Windows Application?

查看:51
本文介绍了如何使用通用 Windows 应用程序将串行数据写入 COM 端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常 C# 应用程序像这样使用 System.IO.Ports:

Typically C# applications use System.IO.Ports like so:

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

但通用 Windows 应用程序不支持 System.IO.Ports,因此无法使用此方法.有谁知道在UWA中如何通过COM端口写入串行数据?

But Universal Windows Applications don't support System.IO.Ports so this method cannot be used. Does anyone know how to write serial data through COM ports in a UWA?

推荐答案

您可以使用 Windows.Devices.SerialCommunicationWindows.Storage.Streams.DataWriter 类:

You can do this with the Windows.Devices.SerialCommunication and Windows.Storage.Streams.DataWriter classes:

这些类提供发现此类串行设备、读取和写入数据以及控制流控制的串行特定属性(例如设置波特率、信号状态)的功能.

The classes provide functionality to discover such serial device, read and write data, and control serial-specific properties for flow control, such as setting baud rate, signal states.

通过将以下功能添加到 Package.appxmanifest:

By adding the following capability to 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();
}

这篇关于如何使用通用 Windows 应用程序将串行数据写入 COM 端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆