Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Linux (Ubuntu) Writing to Serial Properly (For Arduino)

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?

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.

See my overly simple and inefficient test:

#include <iostream>
#include <stdio.h>
using namespace std;

int
main()
{
  FILE *file;
  //Opening device file

  int getnum;

  while (true)
    {
      file = fopen("/dev/ttyACM5", "w");
      cout << ">>" << endl;
      cin >> getnum;
      fprintf(file, "%d", getnum); //Writing to the file
      fclose(file);
    }

}

The while loop is cute, but hardly efficient if allowed to run without waiting for the user. I suspect the redundant fopen fclose use is stupid.

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.

Of course this is all for fun, but as you can see I need to "learn the rules" of serial interaction in C++! Any help or guidance greatly appreciated.


The arduino 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() > 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);
    }
}
like image 335
Orangeman555 Avatar asked Oct 02 '22 13:10

Orangeman555


1 Answers

I wonder why nobody answered this question for so long. Why are you saying this is an inefficient way? It isn't creating a physical file in the filesystem if you're referring to that. This is actually the right way to do it, just don't open and close the file descriptor inside the loop. If you want Serial.read to read a single value send '\n', fprint (file, "%d\n", value).

like image 53
2LayerNN300HU Avatar answered Oct 10 '22 22:10

2LayerNN300HU