Sof*_*per 1 c# serial-port win-universal-app windows-10-iot-core uwp
我正在使用此代码但不工作并抛出此异常:对象引用未设置为对象设备[0]的实例,为我提供空值.
private async void ConnectToSerialPort()
{
string selector = SerialDevice.GetDeviceSelector("COM7");
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
if (devices.Count > 0)
{
DeviceInformation deviceInfo = devices[0];
SerialDevice serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);
Debug.WriteLine(serialDevice);
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();
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ConnectToSerialPort();
}
Run Code Online (Sandbox Code Playgroud)
请帮我删除此错误,我将非常感谢你.请帮忙 :(
您需要在Package.appxmanifest中添加串行设备功能,如下所示:
<Capabilities>
<DeviceCapability Name="serialcommunication">
<Device Id="any">
<Function Type="name:serialPort" />
</Device>
</DeviceCapability>
</Capabilities>
Run Code Online (Sandbox Code Playgroud)
有关更多信息,您可以参考串行设备功能使用.
| 归档时间: |
|
| 查看次数: |
3397 次 |
| 最近记录: |