首页 > 解决方案 > C# 无法打开 STMicro 虚拟 COM 端口

问题描述

我在打开 STMicro USB 虚拟 COM 端口时遇到问题。

当我将设备插入我的 PC 时,COM 端口按原样显示,并且 Windows 设备管理器指示它工作正常。

我在 PC 上有一个 C# 程序,它选择并打开这个端口。

但是,在大约十分之一的尝试中,PC 程序坚持使用 port.open() 命令,大约半分钟后,返回错误“信号量超时期限已过期”。

我编写了一个小小的 C# 程序,它只打开端口。这仍然给出了所指出的行为。

public partial class Form1 : Form
{
    SerialPort port = new SerialPort();
    string portName = "COM1";  // Give it a default to start with


    public Form1()
    {
        InitializeComponent();

        // Populate the COM port selector combobox with available port names
        cmbPortSelect.Items.Clear();

        string[] activePorts = SerialPort.GetPortNames();
        foreach (string availablePort in activePorts)
        {
            cmbPortSelect.Items.Add(availablePort);
        }

        // Declare the serial port
        port = new SerialPort(portName, 9600, Parity.None, 8, StopBits.One);
        port.ReadTimeout = 100;

    }

    private void cmbPortSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cmbPortSelect.SelectedIndex != -1)
        {   // It will get set to -1 (i.e. no selection) in the catch below - we don’t want this selected item change to do anything
            if (port.IsOpen) port.Close();
            port.PortName = (string)cmbPortSelect.SelectedItem;
            System.Threading.Thread.Sleep(50);
            try
            {
                port.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                cmbPortSelect.SelectedIndex = -1;  // Clear the selected item box
            }
        }

    }
}

如果我不使用我的 C# 程序打开端口,而是使用通信程序PuTTY,它每次都有效。

此外,如果我插入具有 FDTI USB 虚拟 COM 端口的设备,它也每次都能正常工作。

我正在使用带有 STMicro VCP 驱动程序 1.3.1 版的 Windows 7,但 Windows 10 和 STMicro 建议我们使用的通用 Microsoft 驱动程序也会出现相同的行为。

Windows 7 有 1.5.1 版本的驱动程序,但是我安装它们时,它报告它们已正确安装,但设备管理器仍然报告 1.3.1 版本。

有没有人注意到任何类似的行为?

标签: c#serial-port

解决方案


这似乎是一个时间问题。尝试将延迟从 50 增加到 200 毫秒并检查差异。正如文档所说:The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.遗憾的是,没有指定实际时间。


推荐阅读