I have something strange happening with my code when trying to connect to a serial port. When using Serial Sample, everything works just fine and it connects on the first try. However, with my code the serial port returns a null.
I have found a workaround by nested the call to write the serial port in a do loop until the serial port is no longer null and it works. It takes, on average, 500 loops to connect and it has always connected. I know it's dangerous because there is the infinite loop if it's always null, so I tried switching the do loop to a for loop. With a for loop, it always returns back as null, even when I iterate it 50,000 times. Has anyone else encountered this and found a better solution? I'm connecting to an Arduino Uno.
The reason I'm not just using the Serial Sample code is because I want to use a drop down menu and use the port name instead of the device id name. My code is below. Thanks.
//lists com ports
private async void listPorts()
{
try
{
string aqs = SerialDevice.GetDeviceSelector();
var dlist = await DeviceInformation.FindAllAsync(aqs);
status.Text = "Select a device and connect";
for (int i = 0; i < dlist.Count; i++)
{
var port = await SerialDevice.FromIdAsync(dlist[0].Id);
ConnectDevices.Items.Add(port.PortName);
}
comConnect.IsEnabled = true;
ConnectDevices.SelectedIndex = 0;
}
catch (Exception ex)
{
status.Text = ex.Message;
}
}
//connects to the selected com port
private async void comConnect_Click(object sender, RoutedEventArgs e)
{
_key = 0;
status2.Text = "";
string aqs = SerialDevice.GetDeviceSelector(ConnectDevices.SelectedItem.ToString());
var dlist = await DeviceInformation.FindAllAsync(aqs);
if (dlist.Count <= 0)
{
status.Text = "No devices found.";
return;
}
try
{
do
{
serialPort = await SerialDevice.FromIdAsync(dlist[0].Id);
status.Text = "Connecting to serial port...";
} while (serialPort == null);
// Configure serial settings
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.BaudRate = 38400;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Handshake = SerialHandshake.None;
status.Text = "Serial port configured successfully.";
I have added the following to package.appmanifest
<Capabilities>
<DeviceCapability Name="serialcommunication">
<Device Id="any">
<Function Type="name:serialPort" />
</Device>
</DeviceCapability>
</Capabilities>