如何使用通用Windows应用程序将串行数据写入COM端口?

时间:2016-04-03 02:16:33

标签: c# serial-port win-universal-app serial-communication

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

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

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

2 个答案:

答案 0 :(得分:3)

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.

By adding the following capability to Package.appxmanifest:

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

Then running the following code:

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();
}

答案 1 :(得分:0)

Microsoft提供了一个示例,该类在名为CustomSerialDeviceAccess的通用Windows应用程序中使用SerialDevice类访问和使用com端口。

Microsoft已将其发布在GitHub上。您可以在这里找到它:

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

Microsoft对示例应用程序说:

  

”该示例允许用户配置串行端口并与之通信   设备。您可以选择以下四种情况之一:

     

使用“设备选择”列表连接/断开连接;配置串口   设备;与串行设备通信;在上注册活动   串行设备”

参考文献:Microsoft,GitHub