串口连接,Readline/ readeexisting不工作
本文关键字:readeexisting 工作 Readline 连接 串口 | 更新日期: 2023-09-27 18:07:12
我正在尝试与另一台机器进行串行连接。我正在使用虚拟串行端口模拟器来尝试这一点。我在超级终端上使用的设置如下所示。我可以看到portopen是true
,但是我无法检查我是否可以写或读。当我尝试ReadLine
方法时,它给出了TimeoutException
,当它读取现有命令时,它什么也不做。DataReceived
也不会被触发。你能帮我一下吗?
private void Page1_Load(object sender, EventArgs e)
{
//Port name can be identified by checking the ports
// section in Device Manager after connecting your device
serialPort1.PortName = "COM14"; // that one works for me
//Provide the name of port to which device is connected
//default values of hardware[check with device specification document]
serialPort1.BaudRate = 115200;
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.None;
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.ReceivedBytesThreshold = 8;
serialPort1.ReadTimeout = 2000;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); //
// Writes data to the Serial Port output buffer
//opens the port
serialPort1.Open();
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
inputData = serialPort1.ReadExisting();
this.Invoke((MethodInvoker)delegate { DoUpdate(); });
}
public void DoUpdate()
{
textOutput.Text = (textOutput.Text + inputData);
}
private void btnReadExist_Click(object sender, EventArgs e)
{
if ((serialPort1.IsOpen == true))
{
serialPort1.WriteLine("something");
string read= serialPort1.ReadExisting();
//string output = serialPort1.ReadLine();
textOutput.Text += read;
}
}
private void Page1_FormClosed(object sender,System.Windows.Forms.FormClosedEventArgs e)
{
// Close the Serial Port
serialPort1.Close();
}
问题似乎是你在两个代码块中阅读:首先,直接在按钮的事件中发送文本之后。其次,您分配了一个事件,该事件在异步调用时读取数据。您应该决定使用哪一个,并删除另一个。