-1

我已经在这里潜伏了一段时间,并且仅仅通过提问就学到了很多东西。不过,我对某些事情感到很困惑。我正在使用C#,并且正在尝试使用 IO.Ports 与 USB 设备进行通信。

我的代码工作假定正确的串行端口,但有时我的设备在插入时会在不同的端口上结束,我希望能够运行我的代码而不必更改一个变量并重新编译。因此,我希望代码轮询用户以获取端口号,尝试打开端口,在端口名称错误时捕获 IOException,然后重新轮询直到给出有效端口。

这是我到目前为止所拥有的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;

namespace USBDev1
{
    class Program
    {
        static void Main(string[] args)
        {
            String portname = "COM";
            SerialPort port = new SerialPort();
            port.BaudRate = 9600;
            bool loopthing = true;

            while (loopthing == true)
            {
                Console.WriteLine("Which port?");
                portname = "COM" + Console.ReadLine();
                try
                {
                    port.PortName = portname;
                    port.Open();
                    loopthing = false;
                }
                catch (System.IO.IOException e)
                {
                    Console.WriteLine("Didn't work, yo");
                    throw (e);
                }
            }

            // Body code
        }
    }
}
4

1 回答 1

1

我不确定你在问什么,但我认为你应该在选择一个之前列出可用的端口。以下代码可能有效;它可以编译,但未经测试。

这也不是一个好方法。更好的方法是在插入设备之前列出端口,然后再次列出端口以查看插入设备后显示的新端口。

SerialPort port;

bool isCorrectPortFound = false;

// Try different ports until a device reacts when a character is written to it
while (!isCorrectPortFound)
{
    // Get all open ports
    string[] ports = SerialPort.GetPortNames();

    // Menu choice for a port to select
    char portSelect = '0';

    // Write the port names to the screen
    foreach (string s in ports)
    {
        portSelect++;
        Console.Write(portSelect);
        Console.Write(". ");
        Console.WriteLine(s);
    }

    Console.WriteLine();

    Console.Write("Select from port 1 to " + portSelect.ToString() + " > ");
    int selectedPort = (Console.Read()) - '0'; // Character value of 1 to ...

    try
    {
        // Assume selectedPort is a valid integer, set baud, etc. as per your choice.
        port = new SerialPort(ports[selectedPort] /* COMportBaudRate, 
                                                     COMportParity, 
                                                     COMportDataBits, 
                                                     COMportStopBits */);

        // OK, port is open, write to the device. The device 
        // must respond visually, blinking a LED or something.
        port.Write("A");

        Console.WriteLine();
        Console.Write("Did the device get your message? (y n) > ");
        int a = (Console.Read()) - 'a';

        if (a + 'a' == 'y')
            isCorrectPortFound = true;
        else
        {
            port.Close();
            port = null;
        }
    }
    catch (Exception ex)
    {
        // Display a message box, exit, etc.
    }
}

// Do other stuff
于 2013-06-16T05:01:29.360 回答