c# - 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 版本。
有没有人注意到任何类似的行为?
解决方案
这似乎是一个时间问题。尝试将延迟从 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.
遗憾的是,没有指定实际时间。
推荐阅读
- mysql - 子查询返回超过 1 行 - 多选 MySQL
- c# - C# 不包含“GetAwaiter”的定义,最好的扩展方法重载需要“Task”类型的接收器
- asp.net - 使用了命名连接字符串,但在应用程序的配置中找不到名称“tumoDB”。.Net 核心 3.0 REST API
- kubernetes - 在 Spinnaker 中映射 kubernates 卷属性
- java - 如何将布尔值传递给java中的存储过程
- apache-kafka - 如何在 Kafka 中删除消费者组成员
- html - 如何在不使用absolute的情况下将元素定位在父元素内
- html - 带有背景图像的多边形的 div 边框(在 CSS 中使用剪辑路径)
- python - 提取与一串单词完全匹配的推文
- javascript - 无论如何禁用删除反应选择中选定选项的“x”?