简体   繁体   English

C#定期从串口读取新行

[英]C# periodic new line reading from serial port

Checked many pages but I still find it unanswered. 检查了很多页面,但我仍然觉得它没有答案。

My problem is as follows. 我的问题如下。 I have a device, connected over RS232 to the computer. 我有一个设备,通过RS232连接到计算机。 The device is sending TWICE a second a line like this: 该设备正在向TWICE发送第二行,如下所示:

"*X;0;bbb;cc;d;eee;f\r\n"

The fields are fixed width numeric fields. 字段是固定宽度的数字字段。 Once every minute the 0 flag raises to 1 and the "cc" changes. 每分钟一次,0标志升至1,“cc”改变。 This number I need then. 这个数字我需要。

In the C# application, I cannot get it working. 在C#应用程序中,我无法使其正常工作。 Tried to use the recieve event to get the data, but the refreshed result needs 10+ seconds to be processed. 尝试使用recieve事件来获取数据,但刷新的结果需要10秒以上才能处理。 This means that 10 seconds after the flag was risen i get the result. 这意味着在旗帜升起10秒后我得到了结果。 Sometimes it takes even longer. 有时需要更长的时间。

I tried first with RecieveEvent. 我先用RecieveEvent尝试过。 I even tried to fill the buffer untill it would fill the line, but again, same result. 我甚至试图填充缓冲区,直到填满线,但同样的结果。 Then I tried with Timer that invokes every 300 ms and reads a line. 然后我尝试使用Timer,每300毫秒调用一次并读取一行。 Still the same problem. 仍然是同样的问题。

So my question is, how to read and process up to date data from serial port? 所以我的问题是,如何从串口读取和处理最新数据?

When reading, the serial port will buffer data. 读取时,串口将缓冲数据。 This will introduce a small delay (but we're talking milliseconds, not tens of seconds). 这将引入一个小延迟(但我们说的是毫秒,而不是几十秒)。 Most serial device drivers will allow you to configure the buffering, too, if it's really critical. 大多数串行设备驱动程序也允许您配置缓冲,如果它真的很重要。

If you call ReadLine, you could introduce more delay, as it will wait until it receives a newline before it returns any data. 如果你调用ReadLine,你可能会引入更多的延迟,因为它会在它返回任何数据之前等到它收到换行符。 Are you sure that your device is sending good newlines? 您确定您的设备正在发送好的换行符吗? Use a terminal emulator program to see exactly what the device is actually sending, as device documentation is often terrible! 使用终端仿真程序可以准确查看设备实际发送的内容,因为设备文档通常很糟糕!

I would Read raw data from the port, and then parse it myself. 我会从端口读取原始数据,然后自己解析它。 You may have to be more careful about receiving partial packets, but you remove all the middle-men from the picture, and you can be more tolerant (eg Not caring whether or not the data has newlines in it). 您可能必须更加小心地接收部分数据包,但是您从图片中删除了所有中间人,并且您可以更宽容(例如,不关心数据是否在其中有新行)。 Start a read and then write out the data you received to the debug console and you'll soon see what your program is receiving and how often, etc. This will also show you if the delay is in the serial port or in your processing of the messages 开始读取,然后将收到的数据写出到调试控制台,您很快就会看到您的程序正在接收的内容以及频率等等。这也将显示延迟是在串口还是处理中消息

You may try serialPort1.readExisting(); 你可以试试serialPort1.readExisting(); then try parsing the data. 然后尝试解析数据。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM