【问题标题】:SerialPort.Open() - The parameter is incorrectSerialPort.Open() - 参数不正确
【发布时间】:2019-05-23 02:18:54
【问题描述】:

我正在尝试在 C# 中打开一个 COM 端口,但我得到一个带有错误消息的 IO 异常:

参数不正确

我看到了这个帖子:SerialPort.Open() --IOException — “The parameter is incorrect.”
它描述了同样的问题,但将 RtsEnable 设置为 true 并没有解决我的问题(没有任何改变)。

这是我的代码:

cmp_Comport.PortName = "COM6";
cmp_Comport.BaudRate = 9600;
cmp_Comport.Parity = Parity.None;
cmp_Comport.StopBits = StopBits.One;
cmp_Comport.DataBits = 8;
cmp_Comport.Handshake = Handshake.None;
cmp_Comport.RtsEnable = true;
cmp_Comport.DataReceived += new SerialDataReceivedEventHandler(CMP_DadaReceived);
cmp_Comport.Open(); // ==> Causes exception

这是完整的异常堆栈跟踪:

在 System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
在 System.IO.Ports.InternalResources.WinIOError()
在 System.IO.Ports.SerialStream.InitializeDCB(Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Boolean discardNull)
在 System.IO.Ports.SerialStream..ctor(字符串端口名,Int32 波特率,奇偶校验,Int32 数据位,StopBits stopBits,Int32 读取超时,Int32 写入超时,握手握手,布尔 dtrEnable,布尔 rtsEnable,布尔丢弃空,字节奇偶校验替换)
在 System.IO.Ports.SerialPort.Open()
在 C:...\MyProject\Comport.cs:line 83 中的 MyProject.Comport.CMP_Open(Int32 ind, String& 错误)

请注意,在其他软件中,例如Hercules,同一个端口打开就好了。

【问题讨论】:

  • 尝试评论前两个旁边的所有cmp_Comport,看看问题发生在哪一个
  • @styx - 在评论除前两个之外的所有内容后仍然存在相同的问题
  • 尝试像这样将 intinalzation 移动到构造函数 cmp_Comport = new SerialPort("COM6", 9600, ....)
  • @styx - 还是同样的问题...
  • 你使用usb适配器吗?它发生在其他计算机上吗?可以添加整个 SerialPort 初始化过程吗?

标签: c# .net serial-port


【解决方案1】:

此异常通常发生在没有底层物理 RS​​232 实现的虚拟(例如 USB)COM 端口上。此类端口不管理状态位,因此SerialPort.Open() 方法在尝试设置串行端口的通信参数时会引发 IOException 错误 87“参数不正确”。

System.IO.Ports.SerialPort 类不支持这种情况,但您可以使用其他实现。

例如,使用SerialPortStream 库(也可在NuGet 中使用),您可以使用SerialPortStream.OpenDirect() 方法打开串行COM 端口而无需设置通信参数:

namespace Vurdalakov
{
    using System;
    using RJCP.IO.Ports;

    class Program
    {
        static void Main(String[] args)
        {
            using (var serialPort = new SerialPortStream("COM1"))
            {
                serialPort.OpenDirect();

                while (serialPort.IsOpen)
                {
                    var ch = (Char)serialPort.ReadChar();
                    Console.Write(ch);
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-23
    • 2015-05-27
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    相关资源
    最近更新 更多