I am using this code but not working and throwing this exception: Object reference not set to an instance of an object devices[0] giving me null value.
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();
}
Please help me to remove this error please , i will very thankful to you . please help :(
You need add serial device capability in Package.appxmanifest like this:
<Capabilities>
<DeviceCapability Name="serialcommunication">
<Device Id="any">
<Function Type="name:serialPort" />
</Device>
</DeviceCapability>
</Capabilities>
For more information you can reference Serial device capability usage.
来源:https://stackoverflow.com/questions/44467220/uwp-serial-port-communication-for-character-write-and-read-uwp-and-arduino