title: C++ Linux (Ubuntu) Writing to Serial Properly (For Arduino)
body: <p><strong>I'd like to know if there is a standard way to communicate with the serial device that is efficient. Should I be using a standard library? If so, which one?</strong></p>
  
  <p>Right now I'm fiddling around getting an LED to light up at a given amount based on number input. (Arduino code below). Just practice stuff.</p>
  
  <p>See my overly simple and inefficient test:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdio.h&gt;
  using namespace std;
  
  int
  main()
  {
    FILE *file;
    //Opening device file
  
    int getnum;
  
    while (true)
      {
        file = fopen("/dev/ttyACM5", "w");
        cout &lt;&lt; "&gt;&gt;" &lt;&lt; endl;
        cin &gt;&gt; getnum;
        fprintf(file, "%d", getnum); //Writing to the file
        fclose(file);
      }
  
  }
  </code></pre>
  
  <p>The while loop is cute, but hardly efficient if allowed to run without waiting for the user. I suspect the redundant <code>fopen</code> <code>fclose</code> use is stupid.</p>
  
  <p>The microcontroller is going to be sensing states of a device and sending signals to the computer. The computer will do the "crunching" of all of these values, and sending messages back to alter the arduino's behavior. Basically the heavy thinking is being delegated to the computer, besides requiring human keyboard input. </p>
  
  <p>Of course this is all for fun, but as you can see I need to "learn the rules" of serial interaction in C++! <strong>Any help or guidance greatly appreciated.</strong></p>
  
  <hr>
  
  <p>The arduino code:</p>
  
  <pre><code>char incomingByte = 0;   // for incoming serial data
  int led = 11;
  int bright;
  void
  setup()
  {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  
  }
  
  void
  loop()
  {
  
    // send data only when you receive data:
    if (Serial.available() &gt; 0)
      {
        // read the incoming byte:
        incomingByte = Serial.read();
  
        switch (incomingByte)
          {
        case '1':
          bright = 10;
          break;
        case '2':
          bright = 50;
          break;
        case '3':
          bright = 255;
          break;
  
        default:
          bright = 0;
          break;
          }
  
        analogWrite(led, bright);
  
        Serial.println(incomingByte);
      }
  }
  </code></pre>