user4527: I want to read the analog values of my ardunio uno into a separate c++ program. On the Arduino I have a serial port initialized for 9600 baud:
int sensorPin = A0;    // select the input pin for the potentiometer

int sensorValue = 0;  // variable to store the value coming from the sensor

void setup() {
Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
} 

The output value should be right around 390, given the current settings. My serial port reading code seems to read the port fine, but only displays some of the characters sometimes.... some of the time, it reads the value fine. other times I get one or 2 of the characters, such as 3, or 39.
#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>    // POSIX terminal control definitions
#include <iostream>     
using namespace std;

int main(){
    const char* device ="/dev/ttyACM0";
/* Open File Descriptor */
//int USB = open( device, O_RDWR| O_NONBLOCK | O_NDELAY );
int USB = open( device, O_RDWR| O_NOCTTY );

/* Error Handling */
if ( USB < 0 ){
cout << "Error " << errno << " opening " << device << ": " << strerror (errno) << endl;
}

/* *** Configure Port *** */
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
   cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
   cout << "Error " << errno << " from tcsetattr" << endl;
}


if ( tcsetattr ( USB, TCSANOW, &tty ) != 0){
cout << "Error " << errno << " from tcsetattr" << endl;
}


/* Allocate memory for read buffer */
char buf [1024];
memset (&buf, '\0', sizeof buf);

/* *** READ *** */
int n = read( USB, &buf , sizeof buf );
cout << "buffer: " << &buf << endl; 
/* Error Handling */
if (n < 0)
{
     cout << "Error reading: " << strerror(errno) << endl;
}

/* Print what I read... */
cout << "Read: " << buf << endl;

close(USB);
 return 0;
}

How can I read the correct value being sent every time?

user20245: A USB connection is actually very complex.  And serial communications (or the CDC class of USB) is only 1 of over a dozen protocols used over USB.  Most cheap embedded processors save money by leaving out this feature.  Most Arduino's use cheap embedded processors.  For instance, the classic Arduino Uno needs a second chip (search for New USB in this link) to even talk Serial over the USB port.  Fortunately this is what Serial.print() does.  It takes care of setting up the Serial protocol over the USB port for you.  And will send your data over that connection.
How you pick up that data at the other end of the USB connection is usually beyond the discussion range of this stack exchange site.  But if you are on a windows machine it will probably be one of the COM ports.  And on Linux it will probably be something like /dev/ttyUSB0 or 1.

user7508: There are a few issues at play here. One is that the Arduino
resets every time you open the serial connection on the PC side. You can
prevent this by putting a 1 µF (or more) capacitor between 5V and
RESET. A second issue is that the tty driver may be keeping old data in
its buffer, and you get this data when you open the connection. The
third issue is that read() returns as soon as it is able to read
some data: it doesn't wait until it has got sizeof buf bytes.
To fix those issues, I suggest:

Have some form of handshake, where the PC sends a request to the
Arduino, and then the Arduino acknowledges and starts to send the
data. The PC program would then discard everything preceding the
acknowledgement.
On the PC, repeatedly read() until you have a full line (which ends
with CRLF). You may want to use a line-oriented stream if you want
the libc to handle this for you: see fdopen(3) setlinebuf(3).

Edit: A very simple example of handshake: the PC sends S (for
“start”), then the Arduino sends OK, then it starts sending the data.
On the Arduino side:
void setup() {
    Serial.begin(9600);

    // Wait for the 'S' (start) command from the computer.
    while (Serial.read() != 'S')
        /* wait */ ;

    // Send acknowledgement.
    Serial.println("OK");
}

A longer “start” command would be more robust, but a bit more complex to
handle on the Arduino. The PC should wait a bit before sending the
command (in case the Arduino is restarting), or maybe send it multiple
times until it gets an answer.

4527: <p>I want to read the analog values of my ardunio uno into a separate c++ program. On the Arduino I have a serial port initialized for 9600 baud:</p>
<pre><code>int sensorPin = A0;    // select the input pin for the potentiometer

int sensorValue = 0;  // variable to store the value coming from the sensor

void setup() {
Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
} 
</code></pre>
<p>The output value should be right around 390, given the current settings. My serial port reading code seems to read the port fine, but only displays some of the characters sometimes.... some of the time, it reads the value fine. other times I get one or 2 of the characters, such as 3, or 39.</p>
<pre><code>#include &lt;stdio.h&gt;      // standard input / output functions
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;     // string function definitions
#include &lt;unistd.h&gt;     // UNIX standard function definitions
#include &lt;fcntl.h&gt;      // File control definitions
#include &lt;errno.h&gt;      // Error number definitions
#include &lt;termios.h&gt;    // POSIX terminal control definitions
#include &lt;iostream&gt;     
using namespace std;

int main(){
    const char* device =&quot;/dev/ttyACM0&quot;;
/* Open File Descriptor */
//int USB = open( device, O_RDWR| O_NONBLOCK | O_NDELAY );
int USB = open( device, O_RDWR| O_NOCTTY );

/* Error Handling */
if ( USB &lt; 0 ){
cout &lt;&lt; &quot;Error &quot; &lt;&lt; errno &lt;&lt; &quot; opening &quot; &lt;&lt; device &lt;&lt; &quot;: &quot; &lt;&lt; strerror (errno) &lt;&lt; endl;
}

/* *** Configure Port *** */
struct termios tty;
struct termios tty_old;
memset (&amp;tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &amp;tty ) != 0 ) {
   cout &lt;&lt; &quot;Error &quot; &lt;&lt; errno &lt;&lt; &quot; from tcgetattr: &quot; &lt;&lt; strerror(errno) &lt;&lt; endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&amp;tty, (speed_t)B9600);
cfsetispeed (&amp;tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &amp;=  ~PARENB;            // Make 8n1
tty.c_cflag     &amp;=  ~CSTOPB;
tty.c_cflag     &amp;=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &amp;=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ &amp; ignore ctrl lines

/* Make raw */
cfmakeraw(&amp;tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &amp;tty ) != 0) {
   cout &lt;&lt; &quot;Error &quot; &lt;&lt; errno &lt;&lt; &quot; from tcsetattr&quot; &lt;&lt; endl;
}


if ( tcsetattr ( USB, TCSANOW, &amp;tty ) != 0){
cout &lt;&lt; &quot;Error &quot; &lt;&lt; errno &lt;&lt; &quot; from tcsetattr&quot; &lt;&lt; endl;
}


/* Allocate memory for read buffer */
char buf [1024];
memset (&amp;buf, '\0', sizeof buf);

/* *** READ *** */
int n = read( USB, &amp;buf , sizeof buf );
cout &lt;&lt; &quot;buffer: &quot; &lt;&lt; &amp;buf &lt;&lt; endl; 
/* Error Handling */
if (n &lt; 0)
{
     cout &lt;&lt; &quot;Error reading: &quot; &lt;&lt; strerror(errno) &lt;&lt; endl;
}

/* Print what I read... */
cout &lt;&lt; &quot;Read: &quot; &lt;&lt; buf &lt;&lt; endl;

close(USB);
 return 0;
}
</code></pre>
<p>How can I read the correct value being sent every time?</p>
 20245: <p>A <a href="https://en.wikipedia.org/wiki/USB" rel="nofollow noreferrer">USB connection</a> is actually very complex.  And <a href="https://en.wikipedia.org/wiki/USB_communications_device_class" rel="nofollow noreferrer">serial communications (or the CDC class of USB)</a> is only 1 of over a dozen protocols used over USB.  Most cheap embedded processors save money by leaving out this feature.  Most Arduino's use cheap embedded processors.  For instance, the classic <a href="https://store.arduino.cc/usa/arduino-uno-rev3" rel="nofollow noreferrer">Arduino Uno</a> needs a <a href="https://learn.adafruit.com/arduino-tips-tricks-and-techniques" rel="nofollow noreferrer">second chip (search for New USB in this link)</a> to even talk Serial over the USB port.  Fortunately this is what <a href="https://www.arduino.cc/reference/en/language/functions/communication/serial/print/" rel="nofollow noreferrer">Serial.print()</a> does.  It takes care of setting up the Serial protocol over the USB port for you.  And will send your data over that connection.</p>
<p>How you pick up that data at the other end of the USB connection is usually beyond the discussion range of this stack exchange site.  But if you are on a windows machine it will probably be one of the COM ports.  And on Linux it will probably be something like /dev/ttyUSB0 or 1.</p>
 7508: <p>There are a few issues at play here. One is that the Arduino
resets every time you open the serial connection on the PC side. You can
prevent this by putting a 1 µF (or more) capacitor between 5V and
RESET. A second issue is that the tty driver may be keeping old data in
its buffer, and you get this data when you open the connection. The
third issue is that <code>read()</code> returns as soon as it is able to read
<em>some</em> data: it doesn't wait until it has got <code>sizeof buf</code> bytes.</p>
<p>To fix those issues, I suggest:</p>
<ol>
<li>Have some form of handshake, where the PC sends a request to the
Arduino, and then the Arduino acknowledges and starts to send the
data. The PC program would then discard everything preceding the
acknowledgement.</li>
<li>On the PC, repeatedly <code>read()</code> until you have a full line (which ends
with CRLF). You may want to use a line-oriented stream if you want
the libc to handle this for you: see fdopen(3) setlinebuf(3).</li>
</ol>
<p><strong>Edit</strong>: A very simple example of handshake: the PC sends <code>S</code> (for
“start”), then the Arduino sends <code>OK</code>, then it starts sending the data.
On the Arduino side:</p>
<pre class="lang-cpp prettyprint-override"><code>void setup() {
    Serial.begin(9600);

    // Wait for the 'S' (start) command from the computer.
    while (Serial.read() != 'S')
        /* wait */ ;

    // Send acknowledgement.
    Serial.println(&quot;OK&quot;);
}
</code></pre>
<p>A longer “start” command would be more robust, but a bit more complex to
handle on the Arduino. The PC should wait a bit before sending the
command (in case the Arduino is restarting), or maybe send it multiple
times until it gets an answer.</p>
