Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C#
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?
Posted

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
 
Share this answer
 
Thanks for your answer!

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

C#
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..
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900