title: Stop to wait for a packet from serial port
body: <p>I'm receiving periodically some data via Serial Port, in order to plot it and do some more stuff. In order to achive this purpose, I send the data from my microcontroller to my computer with a header, which specifies the length of each packet.</p>
  
  <p>I have the program running and working perfectly except a one last detail. When the header specifies a lenght, my program will not stop until it reachs that amount of bytes. So if, for some reason, some data from one packet is missed, the program wait and take the beginning of the next packet...and then start the real problems. Since that moment, every fails.</p>
  
  <p>I thought about rising a Timer every 0.9 seconds ( the packages come every second) who will give a command in order to comeback to wait and reset variables. But I don't know how to do it, I tried but I obtain errors while running. Since IndCom ( see next code) resets in the midle of some function and errors as "Index out of bounds" arises.</p>
  
  <p>I attach my code ( without timer)</p>
  
  <pre><code>private void routineRx(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
      {
          try
          {
              int BytesWaiting;
  
  
              do
              {
                  BytesWaiting = this.serialPort.BytesToRead;
                  //Copy it to the BuffCom
                  while (BytesWaiting &gt; 0)
                  {
                      BuffCom[IndCom] = (byte)this.serialPort.ReadByte();
                      IndCom = IndCom + 1;
                      BytesWaiting = BytesWaiting - 1;
                  }
  
              } while (IndCom &lt; HeaderLength);
              //I have to read until I got the whole Header which gives the info about the current packet
  
              PacketLength = getIntInfo(BuffCom,4);
  
              while (IndCom &lt; PacketLength)
              {
                  BytesWaiting = this.serialPort.BytesToRead;
                  //Copy it to the BuffCom
                  while (BytesWaiting &gt; 0)
                  {
                      BuffCom[IndCom] = (byte)this.serialPort.ReadByte();
                      IndCom = IndCom + 1;
                      BytesWaiting = BytesWaiting - 1;
                  }
               }
  
              //If we have a packet--&gt; check if it is valid and, if so, what kind of packet is
              this.Invoke(new EventHandler(checkPacket));
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.Message);
          }
  
      }
  </code></pre>
  
  <p>I'm new in object-oriented programming and c#, so be clement, please! And thank you very much</p>