我正在使用此代码但没有工作并抛出此异常:对象引用未设置为对象的实例 devices [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();
}
请帮我删除此错误,我将非常感谢你。 请帮忙:(
答案 0 :(得分:5)
您需要在Package.appxmanifest中添加串行设备功能,如下所示:
<Capabilities>
<DeviceCapability Name="serialcommunication">
<Device Id="any">
<Function Type="name:serialPort" />
</Device>
</DeviceCapability>
</Capabilities>
有关详细信息,请参阅Serial device capability usage。