【问题标题】:C# can fail to open STMicro virtual COM portC# 无法打开 STMicro 虚拟 COM 端口
【发布时间】:2019-12-03 03:27:32
【问题描述】:

我在打开 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 端口的设备,它也每次都能正常工作。

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

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

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

【问题讨论】:

  • 您使用的波特率 9600 是否正确?同样为简单起见,请尝试 COM1,2,3... 在更简单的程序中使用所有选项。也不仅仅是更改 PortName。尝试初始化一个新对象。
  • 您的驱动程序似乎不匹配,您是否尝试跟踪error
  • 见@Hans Passant 的回复,好像差不多:stackoverflow.com/questions/13999439/…

标签: c# serial-port


【解决方案1】:

这似乎是一个时间问题。尝试将延迟从 50 增加到 200 毫秒并检查差异。正如doc 所说: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.,遗憾的是,没有指定实际时间。

【讨论】:

    猜你喜欢
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多