Click here to Skip to main content
15,867,305 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
I am reading from hardware device continuosly, the problem is the device stop sending data, i think is problem of my datareceive event but i am not sure of
that.

C#
serialPort.PortName = porta;
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
serialPort.ReadBufferSize = 409600;
serialPort.Open();
CrearTramaConect();
serialPort.Write(TramaConect, 0, TramaConect.Length);


C#
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{

 while (serialPort.BytesToRead >= 14)
     {    
       
      for (int i = 0; i < 14; i++)
      {
          data[i] = (byte)serialPort.ReadByte();
      }

       if (data[13] == (byte)'F')
           {

             data.ToList().ForEach(b => recievedData.Enqueue(b));
             processData();
             //trato los datos en este metodo 
             LineReceived(this, new LineReceivedEventArgs(packet));

            }else{

                  while ((charend != (byte)'F') && serialPort.BytesToRead != 0))
                   charend = (byte)serialPort.ReadByte();

            }
     }
}




C#
public event LineReceivedEventHandler LineReceived;

sp1.LineReceived += new LineReceivedEventHandler(sp1_LineReceived);


void sp1_LineReceived(object sender, LineReceivedEventArgs Args)
        {

            this.Invoke((MethodInvoker)(()=>cargarDatosEnSerie(sender,Args)));

        }



C#
private void cargarDatosEnSerie(object sender, LineReceivedEventArgs Args)
       {

         this.Invoke((MethodInvoker)(() => addPoints(new Dato(Args.packet, false, false, 1, false, false,j))) );

         dataGridView1.Update();

         label1.Text = "numero de puntos: " + j;
         this.Refresh();

       }

byte[] packet;
        private byte[] processData()
        {
            // Determine if we have a "packet" in the queue
           
           if(recievedData.Count>=14)               
                    packet = Enumerable.Range(0, 14).Select(i => recievedData.Dequeue()).ToArray();              
                
          
            return packet;
        }


[EDIT] From comment
That is the data (frame) i receive (always 14 bytes):
68 -->'D'
65 -->'A'
84 -->'T'
0
127 Xh
254 Xl
0
0
115 Yh
51 Yl
5
0
196
70 -->'F'

i do the job with this, (127254) is my X value and 11551 my Y value, i use these to plot it in a chart,my hardware now is sending frames continuosly
x = 1 y = 0,001 'D' 'A' 'T'.............'F'
x = 2 y = 0,002 'D' 'A' 'T'.............'F'
x = 3 y = 0,003 'D' 'A' 'T'.............'F'

All data with this 'D' 'A' 'T'.............'F' frame format is interesting for me, and continuosly read.



C#
<pre lang="C#">thanks George, i have a problem with that

<pre><pre lang="c#">
if (serialPort.BytesToRead > 13) // For example
{
string data = serialPort.ReadLine();




if (data.ToCharArray().Count() == 13)
{



dataArray = Encoding.ASCII.GetBytes(data);


dataArray.ToList().ForEach(b =&amp;gt; recievedData.Enqueue(b));

processData();
LineReceived(this, new LineReceivedEventArgs(dataArray));
}

}

with this line i think

C#
dataArray = Encoding.ASCII.GetBytes(data);


dato: 68---65---84---1---3---63---1---1---1---122---1---1---63---
dato: 68---65---84---1---3---63---1---1---1---123---1---1---63---
dato: 68---65---84---1---3---63---1---1---1---124---1---1---63---
dato: 68---65---84---1---3---63---1---1---1---125---1---1---63---
dato: 68---65---84---1---3---63---1---1---1---126---1---1---63---
dato: 68---65---84---1---3---63---1---1---1---127---1---1---63---
dato: 68---65---84---1---3---63---1---1---1---63---1---1---107--- this will be 128
dato: 68---65---84---1---3---63---1---1---1---63---1---1---106---
dato: 68---65---84---1---3---63---1---1---1---63---1---1---105---
dato: 68---65---84---1---3---63---1---1---1---63---1---1---104---
dato: 68---65---84---1---3---63---1---1---1---63---1---1---111---
dato: 68---65---84---1---3---63---1---1---1---63---1---1---110---
dato: 68---65---84---1---3---63---1---1---1---63---1---1---109---
Posted
Updated 2-Dec-15 2:08am
v4
Comments
Richard MacCutchan 1-Dec-15 9:03am    
Serial devices do not always send the data in a single continuous stream. you need to keep reading until you get a positive indication that there is no more data.
Jesús Álvarez 1-Dec-15 9:28am    
how can i do that?, how to force continuosly reading?
[no name] 1-Dec-15 9:49am    
I would suggest stop doing this "while (serialPort.BytesToRead >= 14)". Instead read everything "Byte by Byte" what is coming on the Serial line and put it to an intermediate buffer. Than evaluate one "level higher", whether a complete message is received.

Of course you need to pay attention of the concurrent Access of the buffer ;)

You need to sit down and think about what you are doing.

Your method serialPort_DataReceived is, most likely, triggered every time a byte is received.

So when a byte is received, what do you do?

Well, if you expect a certain number of bytes to be received you can read the available bytes and put them into a buffer until you fulfill the requirements.

If you are waiting for a end of transmission character, ETX, then you read the incoming bytes and put them into a buffer until you see your ETX character.

This means that you need a "global" buffer to hold received data, and that you only fire an event if your criteria is fulfilled. Then you clear the buffer.

You don't put a loop inside the event. Period.

[UPDATE]
If your data always end with the ASCII character F, you can modify the property SerialPort.NewLine[^]

C#
serialPort.PortName = porta;
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
serialPort.ReadBufferSize = 409600;
serialPort.NewLine = "F";
serialPort.ReadTimeOut = 1000;  // When using ReadLine it is good to set a timeout.


Then in the event handler for the data received you can do something like this
C#
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
    if (serialPort.BytesToRead > 13) // For example
    {
        // ReadLine blocks until the NewLine character appears or time out
        string data = serialPort.ReadLine();

        // The F is not included in the data so if you need it you have to add it again
        // data += "F";

        // Do your stuff
    }
}
 
Share this answer
 
v4
Comments
[no name] 1-Dec-15 10:55am    
yes. a 5.period.
George Jonsson 1-Dec-15 22:52pm    
thanks.
Jesús Álvarez 1-Dec-15 11:50am    
ok, i am going to implement (if i can) yesterday then tell you a feedback. thanks
George Jonsson 1-Dec-15 22:52pm    
I hope you came to a solution.
Sergey Alexandrovich Kryukov 1-Dec-15 14:11pm    
5ed, despite the lack of positive advice. But it's more important to make a first step.
—SA
C#
that is all right, thanks to George, the problem was, coding and decoding, the hardware send me an byte array, when i read from de serial, i recieve this, when i use readLine whitought any decoding, i lost the order of bytes, the solution, encoding the port, and decoding the string when we use read line method 
 
Share this answer
 

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