Cha*_*ton 4 c# serial-port serial-communication win-universal-app
通常,C#应用程序使用System.IO.Ports如下方式:
SerialPort port = new SerialPort("COM1");
port.Open();
port.WriteLine("test");`
Run Code Online (Sandbox Code Playgroud)
但是通用Windows应用程序不支持,System.IO.Ports因此无法使用此方法。有谁知道如何通过UWA中的COM端口写入串行数据?
您可以使用Windows.Devices.SerialCommunication和Windows.Storage.Streams.DataWriter类来执行此操作:
这些类提供以下功能:发现此类串行设备,读取和写入数据,以及控制特定于串行的属性以进行流控制,例如设置波特率,信号状态。
通过将以下功能添加到Package.appxmanifest:
<Capabilities>
<DeviceCapability Name="serialcommunication">
<Device Id="any">
<Function Type="name:serialPort" />
</Device>
</DeviceCapability>
</Capabilities>
Run Code Online (Sandbox Code Playgroud)
然后运行以下代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5761 次 |
| 最近记录: |