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

孤街醉人 提交于 2019-12-22 00:20:52

问题


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


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!