title: Reading Serial Data from Arduino, Corrupted Data
body: <p>I am using an Arduino Due and Visual Studio 2010. I am programming in C/C++. Below you see my programs and after this my explanations of what is going wrong.</p>
  
  <p>This is the really simple code thats on my Arduino. Its sending a lot of A's to the PC.</p>
  
  <pre><code>void setup()
  {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
  }
  
  void loop()
  {
    Serial.println('A');
    delay(1);        // delay in between reads for stability
  }
  </code></pre>
  
  <p>The further code for reading the Serial Port I found over here:
  <a href="http://playground.arduino.cc/Interfacing/CPPWindows" rel="nofollow">http://playground.arduino.cc/Interfacing/CPPWindows</a></p>
  
  <p>And this is my modified version of this code at the moment:</p>
  
  <h2>Header:</h2>
  
  <pre><code>#ifndef SERIALCLASS_H_INCLUDED
  #define SERIALCLASS_H_INCLUDED
  #define ARDUINO_WAIT_TIME 2000
  
  #include &lt;windows.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  class Serial
  {
      private:
          //Serial comm handler
          HANDLE hSerial;
          //Connection status
          bool connected;
          //Get various information about the connection
          COMSTAT status;
          //Keep track of last error
          DWORD errors;
  
      public:
          //Initialize Serial communication with the given COM port
          Serial(char *portName);
          //Close the connection
          //NOTA: for some reason you can't connect again before exiting
          //the program and running it again
          ~Serial();
          //Read data in a buffer, if nbChar is greater than the
          //maximum number of bytes available, it will return only the
          //bytes available. The function return -1 when nothing could
          //be read, the number of bytes actually read.
          int ReadData(char *buffer, unsigned int nbChar);
          //Writes data from a buffer through the Serial connection
          //return true on success.
          bool WriteData(char *buffer, unsigned int nbChar);
          //Check if we are actually connected
          bool IsConnected();
  };
  
  #endif // SERIALCLASS_H_INCLUDED
  </code></pre>
  
  <h2>CPP:</h2>
  
  <pre><code>#include "stdafx.h"
  #include &lt;stdio.h&gt;
  #include &lt;tchar.h&gt;
  #include "SerialClass.h"
  #include &lt;string&gt;
  #include &lt;windows.h&gt;
  #include &lt;assert.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;conio.h&gt;
  
  
  using namespace System;
  using namespace std;
  
  // Serial::Serial looks, if Serial Connection from PC to the Device is proper and everything is working. Then it sets a few Parameters and waits
  Serial::Serial(char *portName)
  {
      //We're not yet connected
      this-&gt;connected = false;
  
      //Try to connect to the given port throuh CreateFile
      this-&gt;hSerial = CreateFileA(portName,
              GENERIC_READ | GENERIC_WRITE,
              0,
              NULL,
              OPEN_EXISTING,
              FILE_ATTRIBUTE_NORMAL,
              NULL);
  
      //Check if the connection was successfull
      //if not...show error
      if(this-&gt;hSerial==INVALID_HANDLE_VALUE)
      {
          //If not success full display an Error
          if(GetLastError()==ERROR_FILE_NOT_FOUND){
              //Print Error if neccessary
              printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);
              Sleep(2000);
          }
          else
          {printf("ERROR!!!");}
      }
      // else = connection is working, then -&gt; continue
      else
      {
          //If connected we try to set the comm parameters
          DCB dcbSerialParams = {0};
  
          //Try to get the current Parameters
          if (!GetCommState(this-&gt;hSerial, &amp;dcbSerialParams))
          {
              //If impossible, show an error
              printf("failed to get current serial parameters!");
          }
          else
          {
              //Define serial connection parameters for the arduino board
  
              dcbSerialParams.BaudRate=CBR_9600;
              dcbSerialParams.ByteSize=8;
              dcbSerialParams.StopBits=ONESTOPBIT;
              dcbSerialParams.Parity=NOPARITY;
  
  
               //Set the parameters and check for their proper application
               if(!SetCommState(hSerial, &amp;dcbSerialParams))
               {
                  printf("ALERT: Could not set Serial Port parameters");
               }
               else
               {
                   //If everything went fine we're connected
                   this-&gt;connected = true;
                   //We wait 2s as the arduino board will be reseting
                   Sleep(ARDUINO_WAIT_TIME);
               }
          }
      }
  }
  
  
  //Has a look if SerialPort is still connected.
  //If yes, it disconnects and closes the Serial Handler.
  Serial::~Serial()
  {
      //Check if we are connected before trying to disconnect
      if(this-&gt;connected)
      {
          //We're no longer connected
          this-&gt;connected = false;
          //Close the serial handler
          CloseHandle(this-&gt;hSerial);
      }
  }
  
  
  // reads data out of Serial Port
  int Serial::ReadData(char *buffer, unsigned int nbChar)
  {
      //Number of bytes we'll have read
      DWORD bytesRead;
      //Number of bytes we'll really ask to read
      unsigned int toRead;
  
      //Use the ClearCommError function to get status info on the Serial port
      ClearCommError(
          this-&gt;hSerial, // Handle to the communications device, CreateFile Function returns this value
          &amp;this-&gt;errors, // a pointer to a variable that receives a mask indicating the type of rror
          &amp;this-&gt;status);// a pointer to a COMSTAT structure in which the devices status information is returned. if this parameter is NULL, no status information is returned
  
  //Check if there is something to read
  if(this-&gt;status.cbInQue&gt;0) // cbInQue: Number of Bytes received by the Serial provider, but not yet read by a ReadFile operation
  {
      //If there is we check if there is enough data to read the required number
      //of characters, if not we'll read only the available characters to prevent
      //locking of the application.
      if(this-&gt;status.cbInQue&gt;nbChar)
          {toRead = nbChar;}
      else
          {toRead = this-&gt;status.cbInQue;}
  
      //Try to read the require number of chars, and return the number of read bytes on success
      if(ReadFile(
         this-&gt;hSerial,   // Handle to a device
         buffer,          // a pointer to the buffer that receives the data read from a file or device
         toRead,          // NumberofBytesToRead: the maximum number of bytes to be read
         &amp;bytesRead,      // NumberofBytesRead: a pointer to the variable that receives the number of bytes read when using a synchronours hFile parameter.
              NULL)           // Overlapped
              &amp;&amp; bytesRead    // Value of bytesRead after ReadFile function
              != 0)
          {return bytesRead;
          Sleep(1000);}   // returns Value of BytesRead
      }
      //If nothing has been read, or that an error was detected return -1
      return -1;
  }
  
  
  
  bool Serial::IsConnected() // simply returns connection status
  {
      //Simply return the connection status
      return this-&gt;connected;
  }
  </code></pre>
  
  <h2>Main:</h2>
  
  <pre><code>// application reads from the specified serial port and reports the collected data
  int _tmain(int argc, _TCHAR* argv[])
   {
       printf("Welcome to the serial test app!\n\n");
       Serial* SP = new Serial("\\\\.\\COM3");    // adjust as needed
  
       if (SP-&gt;IsConnected())
          printf("We're connected");
  
       // defines how much Data will be catched
       // don't forget to pre-allocate memory
  
          char incomingData[1025] = "";
          incomingData[1024]='\0';
  
          int dataLength = 1024; // maximum Length of one DataBit/Word
          int readResult = 0;
  
          // gives out the Number! of DataBits that could be collected/catched
          readResult = SP-&gt;ReadData(incomingData,dataLength);
  
          printf("Bytes read: (-1 means no data available) %i\n",readResult);
  
  
          // transforms the char incomingData into a String and prints it
  
          std::string test(incomingData);
          printf("%s \n", incomingData);
  
          printf("Bytes read: (-1 means no data available) %i\n",readResult);
  
          Sleep(10000);
     }
  </code></pre>
  
  <p>So now here is my problem:</p>
  
  <p>The programm works fine, as long as the Amount of Bits I am sending from the Arduino is less than DataLength. (here = 1024) I got those less bits just through setting the Delay from the Arduino programm quite high (~100ms).
  Then I have a console window with an Output similar to this:</p>
  
  <pre><code>A
  A
  A
  A
  A
  ... goes on like this
  </code></pre>
  
  <p>But if the Arduino sends more than 1024 Bits (Delay ~ 1ms)/ the PC receices more Bits than the Value of DataLength, something in the Serial::ReadData Loop seems to get wrong.
  My Console Output is than a little bit corrupted and some Bits look like this:</p>
  
  <pre><code>A
  ßA
  
  A A
  A
  ... goes on similar to this.
  </code></pre>
  
  <p>What is wrong with my program? I thought that it could be, that one parameter of the ReadFile() Function is not right, but I do not know what to change and I am not 100% sure about this.</p>