title: How to capture and store sensor data from Arduino into C++
body: <p>I am writing a code to capture serial readings from the Arduino to C++</p>
  <p>Is there a way to capture the readings line by line and then store it into an array? I have read another <a href="https://stackoverflow.com/questions/19894323/how-to-minimize-serial-communication-read-errors-from-a-arduino?answertab=votes#tab-top">post</a> similar to mine, but I am still unable to apply it.</p>
  <p>Any help is greatly appreciated, thank you.</p>
  <p>Environment setup:</p>
  <ul>
  <li>Arduino UNO</li>
  <li>ADXL 335 accelerometer</li>
  <li>Ubuntu 16.04</li>
  <li>C++</li>
  </ul>
  <p>[Updated] applied solution from Bart</p>
  <h2>Cpp file</h2>
  <p>The reason why I added the &quot;for-loop with print and break&quot; is to analyze the array contents.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;iostream&gt;
  #include &lt;unistd.h&gt;
  
  using namespace std;
  
  char serialPortFilename[] = &quot;/dev/ttyACM0&quot;;
  
  int main()
  {
      char readBuffer[1024];
  
      FILE *serPort = fopen(serialPortFilename, &quot;r&quot;);
  
      if (serPort == NULL)
      {
          printf(&quot;ERROR&quot;);    
          return 0;
      }   
  
      while(1)
      {                           
          usleep(1000); //sync up Linux and Arduino       
          
          memset(readBuffer, 0, 1024);
          fread(readBuffer, sizeof(char),1024,serPort);       
      
          for(int i=0; i&lt;1024; i++){
              printf(&quot;%c&quot;,readBuffer[i]);     
          }
          break;
      }
      
      return 0;
  }
  </code></pre>
  <h2>Ino file</h2>
  <p>Fetching data from the Accelerometer</p>
  <pre><code>#include &lt;stdio.h&gt;
  
  const int xPin = A0;
  const int yPin = A1;
  const int zPin = A2;
  
  void setup() {
    Serial.begin(9600);
  }
  
  void loop() {
    int x = 0, y = 0, z = 0;
    
    x = analogRead(xPin);
    y = analogRead(yPin);
    z = analogRead(zPin);
    
    char buffer[16];
    int n;
    n = sprintf(buffer,&quot;&lt;%d,%d,%d&gt;&quot;,x,y,z);
    
    Serial.write(buffer);
  }
  </code></pre>
  <h2>Results</h2>
  <p>Running the code for three times
  <a href="https://i.stack.imgur.com/9WeGl.jpg" rel="nofollow noreferrer">Click Here</a></p>
  <p>The ideal outputs should be</p>
  <pre><code>&lt;a,b,c&gt;&lt;a,b,c&gt;&lt;a,b,c&gt;...
  </code></pre>
  <p>but right now, some of the outputs has the values inside &quot;corrupted&quot; (please <a href="https://i.stack.imgur.com/9WeGl.jpg" rel="nofollow noreferrer">see</a> the fourth line from the top).</p>
  <p>Even if use the start and end markers to determine a correct dataset, the data within the set is still wrong. I suspect the issue lies with the char array from C++, due to it being unsynchronized with Arduino. Else I need to send by Bytes from Arduino (not really sure how)</p>