与C#uwp的串行设备通信

问题描述

我正在尝试使用c#开发一个简单的uwp应用程序以进行串行通信。我有一个能够与腻子终端正确通信的stm32板。 Putty的串行设置为:9600波特,8位,1位停止,奇偶校验无,流控制xon / xoff。当我写“ 1”字符时,LED指示灯亮,我看到响应“ ledon”;当我写“ 0”字符时,LED指示灯熄灭,我看到“ ledoff”消息。 现在,我无法使用uwp C#将字节发送给董事会。我读了许多类似的问题,但没有找到任何实用程序。 我的代码可以正确找到端口,并且我已经提供了串行功能。在阅读其他问题时,我还从ftdichip更新了VCP驱动程序。 我以这种方式打开端口:

        private async void OpenDevice(){
        try
        {
            usbSerialGateway = await SerialDevice.FromIdAsync(usbSerialDevice.Id);
            usbSerialGateway.Baudrate = 9600;
            usbSerialGateway.DataBits = 8;
            usbSerialGateway.Parity = SerialParity.None;
            usbSerialGateway.StopBits = SerialStopBitCount.One;
            usbSerialGateway.Handshake = SerialHandshake.XOnXOff;
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.Message.ToString());
        }
        finally
        {
            Debug.WriteLine("Opened device for communication.");
        }

    }

有断点,我看到usbSerialDevice.Id =“ \\?\ USB#VID_0483&PID_5740#6D873F814953#{86e0d1e0-8089-11d0-9ce4-08003e301f73}”和FromIdAsync没有任何异常。

我以这种方式发送一个字节后:

        public void SendByte(byte b){
        try
        {
            if (usbSerialGateway != null)
            {
                // Writing a byte to the serial device.
                DataWriter dw = new DataWriter(usbSerialGateway.OutputStream);
                dw.WriteByte(b);
            }
        }
        catch (Exception)
        {
            Debug.WriteLine("byte not sent");
        }
    }

我使用带有按钮的SendByte并将字节写入文本框中,因此我使用byte.Parse(text)转换来获取字节。我知道腻子会发送一个字符,所以我写49来发送“ 1”。

对于功能,我将其写入package.manifest:

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

请帮助我!我要疯了!谢谢

解决方法

我解决了这个问题:

我写

await dw.StoreAsync();

之后

dw.WriteByte(b)

,现在可以使用了。我必须添加异步修改器