Share via

UWP Serial Port Returns null whenever serialPort = await SerialDevice.FromIdAsync(deviceId) is run

Michael Chestnut 1 Reputation point
2022-12-16T17:15:51.557+00:00

I am trying to get the serial port information for the following code but it keeps returning null the device id is coming back so I'm not sure why is isn't working?

        string qFilter = SerialDevice.GetDeviceSelector("COM3");  
        DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter);  

        if (devices.Any())  
        {  
            string deviceId = devices.First().Id;  
            Debug.WriteLine(" This is the device ID: " + deviceId);  
            await OpenPort(deviceId);  
        }  

        ReadCancellationTokenSource = new CancellationTokenSource();  

        while (true)  
        {  
            Debug.WriteLine("Listen function is about to run.");  
            await Listen();  
            // added to serial code to break from infinite loop add  
            // console log here to see if data is being read correctly  
            // in listen function  
            break;  

        }  

The following open port is getting an Id but the serial port is null please advise.

private async Task OpenPort(string deviceId)
{
Debug.WriteLine("OpenPort Function has started");
serialPort = await SerialDevice.FromIdAsync(deviceId);
Debug.WriteLine("SerialPort:", serialPort);
if (serialPort != null)
{
Debug.WriteLine("SerialPort not null in Openport Function");
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.BaudRate = 9600;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Handshake = SerialHandshake.None;
}
}

The device I am trying to connect to is:

https://witmotion-sensor.com/collections/6-axis-bluetooth-2-0-accelerometer/products/bluetooth-accelerometer-inclinometer-bwt61cl-mpu6050-high-precision-6-axis-gyroscope-anglexy-0-05-accuracy-acceleration-with-kalman-filter-100hz-high-stability-6dof-data-logger-for-arduino?variant=40749736722629

Developer technologies | Universal Windows Platform (UWP)

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.