Softdeveloper
Softdeveloper

Reputation: 21

UWP serial port communication for character write and read (UWP and Arduino)

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 :(

Upvotes: 1

Views: 5023

Answers (1)

Rita Han
Rita Han

Reputation: 9710

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.

Upvotes: 7

Related Questions