2017-06-09 91 views
2

我正在使用此代碼但不工作並拋出此異常:未將對象引用設置爲對象實例 devices [0]給出空值。用於字符寫入和讀取的UWP串行端口通信(UWP和Arduino)

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

發生在 –

+0

serialDevice哪行的例外呢?是給零例外... – Softdeveloper

+0

請編輯您的問題,添加該細節 –

回答

5

您需要Package.appxmanifest添加串行設備的能力是這樣的:

<Capabilities> 
    <DeviceCapability Name="serialcommunication"> 
     <Device Id="any"> 
     <Function Type="name:serialPort" /> 
     </Device> 
    </DeviceCapability> 
    </Capabilities> 

對於您可以參考Serial device capability usage更多信息