Problems with serial device communication in UWP

帅比萌擦擦* 提交于 2019-12-06 06:18:36

问题


I have a peculiar problem.

I am trying to communicate with a peripheral unit that requires serial communication in a UWP project. I am using Windows.Devices.SerialCommunication.

For purpose of demonstration, I made a new page that has two buttons, with two different click handlers. One for opening the port, and other for sending messages to the peripheral.

One handler is:

    SerialDevice device;

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {
         string selector = SerialDevice.GetDeviceSelector("COM7");
         DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
             if (devices.Any())
             {
                 DeviceInformation deviceInfo = devices.First();
                 device = await SerialDevice.FromIdAsync(deviceInfo.Id);
                 //*********************
                 device.BaudRate = 9600;
                 device.DataBits = 8;
                 device.Parity = SerialParity.None;
                 device.StopBits = SerialStopBitCount.One;
                 device.ReadTimeout = device.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                 device.Handshake = SerialHandshake.None;
             }
             _dataReader = new DataReader(device.InputStream);
             _dataWriter = new DataWriter(device.OutputStream);
    }

Peripheral has a red light on it when I enable the power supply. When the line above //********* is executed, the light is switched off. The peripheral doesn't respond to any messages then. When I stop the program, the light switches back on.

I made a .NET Framework app which works perfectly. It is fully functional. I used System.IO.Ports there. I noticed something:

If I extract and run only this part of the code in .NET Framework app:

SerialPort comPort = new SerialPort();            
_ComPort.PortName = PortName;
_ComPort.BaudRate = BaudRate;
_ComPort.DataBits = 8;
_ComPort.Parity = Parity.None;
_ComPort.StopBits = StopBits.One;
_ComPort.DataReceived += new SerialDataReceivedEventHandler(_ComPort_DataReceived);
_ComPort.Open();

Nothing more.

And run the UWP app again, the port opens perfectly, the lamp is red, and the device responds to messages. I can switch off the device, and initialize it from the UWP app as many times as I want to. When I restart my computer, I can't initialize the device from the UWP app again, (until I run the said block of code from .NET Framework app).

If you want to know, the peripheral is Bill to Bill unit made by Suzo Happ.

I didn't make any mistakes regarding property initialization in UWP.

来源:https://stackoverflow.com/questions/49256707/problems-with-serial-device-communication-in-uwp

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