自动串行读取 [英] Serial Read Automatically

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

问题描述

大家好...
我已经创建了一个应用程序,并且想与外部设备进行串行通信.设备在未指定的时间发送数据.因此,我编写了以下代码:

Hello to everyone ...
I have created an application and I want to communicate Serial with a external device. The device sends the data at unspecified period. For this reason I have written the following code:

public string Read()
       {
           String DataReceived = "";
           try
           {
               DataReceived = Serial_port.ReadLine().ToString();
               return (DataReceived);
           }
           catch
           {
               return (DataReceived="");
           }
       }


而当我想阅读时:


and when i want to read:

 if (Serial_port.IsOpen == false)
    {
        Connect();
        Write("Conn?");
    }

String read_fr = Read();


但是,我不知道设备多久发送一次数据.
我怎么能自动从设备中读取数据?


But, I do not know how often the device sends data.
How can i reading data from the device automatically?

推荐答案

什么都没有自动"发生.仅在编程时才读取数据.如果只是需要掌握串行通信的思想.正如您所描述的,一切都发生了,使用端口几乎是不可能的.实际上,一切都好得多.当一方发送一些数据时,您可以随时阅读.如果您读取数据,但尚未发送任何数据,则在数据到达之前,您的呼叫将被阻止.串行连接可串行化数据交换.当您写入数据时,也会发生类似的情况.由于具有阻塞的调用的性质,最好在单独的线程中读取数据.

—SA
Nothing happens "automatically". You only read the data if you program it. If just need to grasp the idea of serial communications. It everything happened as you describe, working with the port would be nearly impossible. In reality, everything is much better. When one sides sends some data, you can read it at any pace. If you read data, and no data is sent yet, your call is get blocked until the data arrives. Serial connection serializes data exchange. Something similar happens when you write data. Due to the nature of calls with blocking, it''s the best to read data in a separate thread.

—SA


感谢您的回答!

好的,我尝试将read调用放在计时器中.

Thanks for your answer!

Ok I try to put the read call in a timer.

private void timer_Serial_Tick(object sender, EventArgs e)
  {
        String read_fr = Read(); 
        if(read_fr != "")  richTextBox2.Text += read_fr;
	// . . . 
  }





Timer frequency (read) = 5ms   <-   external devise frequency (send) = 10ms



但是,当我这样做时,还有另一个问题.由于数据发送非常快,因此程序可能无法读取它们,因此会填满缓冲存​​储器.因此,即使关闭外部设备,程序也会继续(几秒钟)以读取数据(显然是从内存缓冲区中读取数据).这对我不好,因为这意味着程序无法实时读取数据.
有什么方法可以更快地读取数据,或者至少每次填充缓冲区时都要清理缓冲区?我不在乎是否会丢失一些数据..



But when I do this there is another problem. Because The data is sent very quickly, probably the program can''t to read them ,consequently fills the buffer memory. So even if you switch off the external device, the program continues (for a few seconds) to read data (Obviously from the memory buffer). This is not good for me because this means that program can not read data at the real time.
Is there any way to reading the data more faster, or at least to clean the buffer each time it fills? I do not care if some data will be lost..


这篇关于自动串行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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