title: VisualStudio Visual C# DataReceived Firing Erratically (Receiving Data From Arduino)
body: <p>I'm writing a program in C# in VisualStudio. The basic way it works is that I have my device sampling at 250 samples per second (21 byte packets), relaying data to a Teensy 3.2 which is then relaying it to the computer via USB for processing. </p>
  
  <p>I'm using serialPort_DataReceived to figure out when I received data, with ReceivedBytesThreshold set to 8. If I'm understanding this correctly, whenever it receives at least 8 bytes, it fires the serialPort.DataReceived event and go from there. However, what happens with my program is it fires after it receives 4095 bytes, then it fires after 1 byte, then after 4095 etc. </p>
  
  <p>Also, I swapped out the Teensy for an Arduino Due. In this case it's a lot more stable, firing after every packet as expected, with the exception of the weird 1 byte packets firing after 4095 bytes have been sent. If I crank up the device to 8000 samples per second (the target rate) I start getting serialPort.DataReceived firing after every 3 packets or so. I figured it was the speed of the Arduino slowing it down, which is why I switched to the Teensy, as it runs a lot faster.</p>
  
  <p>I know the sampling device is running fine, as I have three of them and swapping them out provides the same result, and they're designed to handle up to 16000 samples per second. Likewise, I used Realterm to view the incoming data stream and it seems to be constant, and not chunks, so I figure its something in my code. The relevant bits are below.</p>
  
  <pre><code>public Form1()
      {
          InitializeComponent();
          serialPort1.PortName = "COM13";
          serialPort1.BaudRate = 115200;
          serialPort1.DataBits = 8;
          serialPort1.ReceivedBytesThreshold = 21;
          serialPort1.RtsEnable = true;
          serialPort1.DtrEnable = true;
          serialPort1.Handshake = System.IO.Ports.Handshake.XOnXOff;
      }
  private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
      {
          byte[] buffer = new byte[serialPort1.ReadBufferSize];
          int bytesRead = serialPort1.Read(buffer, 0, buffer.Length);
          RxString = BitConverter.ToString(buffer, 0, bytesRead);
          fixedString = RxString.Replace("-", "");
          file.WriteLine(fixedString);
          file.WriteLine("THIS IS A TEST");
          this.BeginInvoke(new EventHandler(graph)); 
          this.BeginInvoke(new EventHandler(DisplayText));
      }
  </code></pre>
  
  <p>Here are some images of the output.
  Teensy: <a href="http://i.imgur.com/0qzIpaT.png" rel="nofollow">http://i.imgur.com/0qzIpaT.png</a>
  Due: <a href="http://i.imgur.com/5O3fpPo.png" rel="nofollow">http://i.imgur.com/5O3fpPo.png</a></p>
  
  <p>Note for this the header is B6B0C0</p>