C#串口问题 [英] C# serial port issues

查看:80
本文介绍了C#串口问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。



我从串口读取数据时遇到了一些麻烦。

我每秒从两个传感器发送数据a; -peperated string并想要读取它们并不断更新两个文本框。



当我尝试使用ReadExcisting()从串口读取数据时,Iam得到更多然后只是两个值。 Readline()似乎也不起作用。



任何帮助都会很棒:-)



提前致谢,



Michael



我的尝试:



Hi everyone.

Iam having some trouble reading data from my serial port.
Iam sending data from two sensors every second as a ;-seperated string and want to read them and update two textboxes continously.

When I try to read data from the Serial port with ReadExcisting() Iam getting more then just the two values. Readline() doesn't seem to work either.

Any help woule be great:-)

Thanks in advance,

Michael

What I have tried:

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string inData = sp.ReadExisting();
    data = inData.Split(delimiterChars);

    if(data.Contains("Temp1"))
    {
        Temp1txt.Invoke(this.myDelegate, new Object[] { data });
    }
    else if (data.Contains("Temp2"))
    {
        Temp2txt.Invoke(this.myDelegate, new Object[] { data });
    }

    richBox1.Invoke(new Action(() => { richBox1.AppendText(data[1]); }));
    richBox1.Invoke(new Action(() => { richBox1.SelectionStart = richBox1.Text.Length; }));            
    richBox1.Invoke(new Action(() => { richBox1.ScrollToCaret(); }));
}

推荐答案

ReadExisting 读取内部可用的所有数据输入缓冲区。这可能是多个数据集,如果之前的读取时间太长,也可能是不完整的最后一个数据集。



所以你需要某种检测来区分数据集以及最后的数据是否完整。这取决于您的数据格式。通常,数据集由换行终止,然后可以使用换行。如果是这样,可以使用 ReadLine (并且应该使用它,因为它使处理数据更加简单)。



但是当 ReadLine 没有返回时,似乎没有或不同的行结束指示符。如果有不同的指标,您可以使用 SerialPort.NewLine属性(System.IO.Ports) [ ^ ]让 ReadLine 在收到该字符时返回。



因此它取决于传感器使用的行/数据集指示符的结尾。
ReadExisting reads all data available in the internal input buffer. This might be multiple data sets if the previous read was too long ago and might also be an incomplete last data set.

So you need some kind of detection to differentiate between data sets and if the last data are complete. This depends on the format of your data. Often a data set is terminated by a line feed which can then be used. If so, ReadLine can be used instead (and should be used because it makes processing the data much simpler).

But when ReadLine does not return, there seems to be no or a different end of line indicator. If there is a different indicator, you can set it using the SerialPort.NewLine Property (System.IO.Ports)[^] to let ReadLine return when that character is received.

So it depends on the end of line / data set indicator that is used by your sensors.


谢谢!



我只是从微控制器发送一个完美的新行字符!



祝你好运,



Michael
Thanks!

I just send a new line character from Microcontroller which works perfectly!

Best regards,

Michael


这篇关于C#串口问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆