c#串口通讯 [英] c# Serial Communication
问题描述
我在c#中编写了一个代码,用于通过串行通信接收数据并将其显示在文本框中。我能够做到这一点。但我收到以下格式的数据,例如
1234 2345 3456 5667
或
1234 3245 5678
但我希望每个传入的字节都应该覆盖前一个字节,在文本框中我们只能看到1个字节,然后是另一个字节覆盖前一个字节。 />
请建议怎么做?
我的ser comm代码如下:
I have written a code in c# for receiving data through serial communication and display it in a text box. I am able to do that. But I am receiving data in following format, e.g.
1234 2345 3456 5667
or
1234 3245 5678
But I want that every incoming byte should overwrite the previous byte and in the text box we should see just 1 byte and then another byte overwriting the previous one.
Please suggest how to do that?
My code for ser comm is as follows :
private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = SerialPort.ReadExisting();
this.Invoke(new EventHandler(DisplayText)); }
private void DisplayText(object sender, EventArgs e)
{
txtIncomingData.AppendText(RxString);
}
推荐答案
你误解了Control.Invoke
。这不是事件调用,因此您的对象发送者
和EventArgs
参数是多余的。有了这个假设的人为限制,你做了一件坏事:将文本传递给相对于你的方法的外部上下文。相反,您应该使用您需要的任何签名的事件委托:
You misunderstoodControl.Invoke
. This is not event invocation, so yourobject sender
andEventArgs
arguments are superfluous. Having this made-up artificial limitation, you have done bad thing: passing the text through the outer context relative to your method. Instead, you should use the event delegate with any signature you need:
string newData = SerialPort.ReadExisting(); // local variable to be used in next line
this.Invoke(new System.Action<string>((data) => {
txtIncomingData.AppendText(data);
}), newData);
如果你需要覆盖字符,不要附加,假设 txtIncomingData
是你的文本框,替换
If you need to override the character, not append, assuming txtIncomingData
is you text box, replace
txtIncomingData.AppendText(data);
with
with
txtIncomingData.Text = data;
下面的解决方案有效,但它在数据之间提供空白字节。
The solution below works, but it gives blank bytes in between data.
SerialPort serialPort;
private delegate void SetTextDeleg(string text);
private void Form1_Load(object sender, EventArgs e)
{
serialPort= new SerialPort("COM6", 4800, Parity.None, 8, StopBits.One);
serialPort.Handshake = Handshake.None;
serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
serialPort.ReadTimeout = 500;
serialPort.WriteTimeout = 500;
serialPort.Open();
}
private void btnStart_Click(object sender, EventArgs e)
{
try
{
if(!serialPort.IsOpen)
serialPort.Open();
}
catch (Exception ex)
{
MessageBox.Show("Could not open Serial Port");
}
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
string data = serialPort.ReadLine();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}
private void si_DataReceived(string data)
{
txtIncomingData.Text = data.Trim();
}
这篇关于c#串口通讯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!