Mar*_*hal 7 .net c# serial-port
我编写了以下代码来配置MainForm加载时的串口.在第一次运行时,它会IOException在端口打开时给出,说明参数不正确.但是,当我重新启动应用程序时,它工作正常.只有在启动计算机后第一次运行应用程序时才会出现异常,然后它才能正常工作,直到下次重新启动计算机.
private void Main_Load(object sender, EventArgs e)
{
this.serialPort1.PortName = "COM3";
this.serialPort1.BaudRate = 9600;
this.serialPort1.DataBits = 8;
this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
this.serialPort1.Open(); //Exception comes here
this.serialPort1.WriteLine("AT#cid=1" + System.Environment.NewLine);
}
Run Code Online (Sandbox Code Playgroud)
执行细节:
System.IO.IOException未被用户代码处理
Message ="参数不正确.\ r \n"Source ="System"
堆栈跟踪:在System.IO.Ports.InternalResources.WinIOError(的Int32的errorCode,字符串str)在System.IO.Ports.InternalResources.WinIOError()在System.IO.Ports.SerialStream.set_RtsEnable(布尔值)System.IO. Ports.SerialStream..ctor(字符串PORTNAME,的Int32波特率,奇偶校验位,数据位的Int32,停止位停止位,的Int32 readTimeout,的Int32 writeTimeout,握手握手,布尔dtrEnable,布尔rtsEnable,布尔discardNull,字节parityReplace)在System.IO.Ports. SerialPort.Open()在JKamdar.Main.Main_Load(对象发件人,EventArgs e)在d:\项目\ JKamdar\JKamdar\Main.cs:线264处系统System.Windows.Forms.Form.OnLoad(EventArgs的) .Windows.Forms.Form.OnCreateControl()在System.Windows.Forms.Control.CreateControl(布尔fIgnoreVisible)在System.Windows.Forms.Control.CreateControl()在System.Windows.Forms.Control.WmShowWindow(邮件&m)在System.Windows.Forms.Control.WndProc在System.Windows.Forms.ScrollableControl.WndProc在System.Windows(邮件&m)(邮件&m).Forms.ContainerControl.WndProc(消息&m)上System.Windows.Forms.Form.WmShowWindow在System.Windows.Forms.Control.ControlNativeWindow.OnMessage在System.Windows.Forms.Form.WndProc(邮件&m)(邮件&m) (消息&m)上在System.Windows.Forms.NativeWindow.Callback System.Windows.Forms.Control.ControlNativeWindow.WndProc(邮件&m)(IntPtr的的HWND,MSG的Int32,IntPtr的WPARAM,IntPtr的LPARAM)的InnerException:
请尝试使用this.serialPort1.RtsEnable = true
根据异常的堆栈跟踪建议
at System.IO.Ports.SerialStream.set_RtsEnable(Boolean value)
at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
at System.IO.Ports.SerialPort.Open()
Run Code Online (Sandbox Code Playgroud)