用于字符读写的 UWP 串口通信(UWP 和 Arduino)

UWP serial port communication for character write and read (UWP and Arduino)(用于字符读写的 UWP 串口通信(UWP 和 Arduino))
本文介绍了用于字符读写的 UWP 串口通信(UWP 和 Arduino)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码但不工作并抛出此异常:对​​象引用未设置为对象的实例devices[0] 给我空值.

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

推荐答案

你需要像这样在 Package.appxmanifest 中添加串口设备功能:

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>

更多信息可以参考串口设备能力使用.

这篇关于用于字符读写的 UWP 串口通信(UWP 和 Arduino)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)