首页 > 解决方案 > 使用 c# uwp 进行串行设备通信

问题描述

我正在尝试在 C# 中开发一个简单的 uwp 应用程序用于串行通信。我有一个能够与腻子终端正确通信的 stm32 板。Putty 的串口设置为:9600baud、8bit、1bit stop、parity none、flowcontrol 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>

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

标签: c#uwpserial-portcdc

解决方案


I SOLVED THE ISSUE:

i write

await dw.StoreAsync();

after

dw.WriteByte(b)

and now it work. I had to add async modifier


推荐阅读