[英]serial port reading multiple lines
I have a board which I am trying to communicate with. 我有一个董事会要与之交流。 When I give it some commands it should return string messages back and should get posted in a textbox.
当我给它一些命令时,它应该返回字符串消息,并且应该发布在文本框中。 My problem is when the device has to return multiple lines of text only 1 of the lines gets posted.
我的问题是,当设备必须返回多行文本时,只有1行被发布。 I have tried also with ReadExisting instead of ReadLine but after one command I get only empty strings back.
我也尝试过用ReadExisting代替ReadLine,但是在执行一个命令后,我只得到空字符串。
public partial class Form1 : Form
{
private string x;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
timer1.Start();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text);
textBox1.Clear();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(x))
{
}
else
{
textBox2.AppendText(x + "\n\r");
x = "";
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
x = serialPort1.ReadLine();
//x = serialPort1.ReadExisting();
}
private void Form1_Closing(object sender, EventArgs e)
{
serialPort1.Close();
timer1.Stop();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
You're always better off avoiding DataReceived
and just using BaseStream
. 最好避免使用
DataReceived
而只使用BaseStream
。 Like this: 像这样:
private async void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
using (var reader = new StreamReader(serialPort1.BaseStream)) {
while (serialPort1.IsOpen) {
string x = await reader.ReadLineAsync();
textBox2.AppendText(x + "\r\n");
}
}
}
The await
keyword silently manages synchronization back to the UI thread -- you don't need Invoke
, you don't get cross-thread failures, you don't get a second invocation of your event handler triggered while the first one is still running, you don't get race conditions from multiple threads accessing the same variable. await
关键字以静默方式管理返回到UI线程的同步-您不需要Invoke
,您不会遇到跨线程故障,您不会在第一个仍在运行时触发事件处理程序的第二次调用,您不会从访问同一变量的多个线程获得竞争条件。 Much easier to get right. 更容易正确。
As a style issue, I wouldn't put this code directly in your Form Load
event handler, I would put it in a suitably named helper function ( OpenAndReadSerial()
perhaps) and call that from overridden OnLoad()
. 作为样式问题,我不会将此代码直接放入您的Form
Load
事件处理程序中,而是将其放入适当命名的帮助器函数(也许是OpenAndReadSerial()
)中,并从覆盖的OnLoad()
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.