0

I'm trying to communicate with an Arduino micro-controller. This is very easy to do in C#, but I can't figure it out in c++. Here is my arduino code...

void loop()
{
  if (Serial.available() > 0)
  {
    byte input = Serial.read();
    Serial.write(input);
  }
}

So anything you send to the arduino will just get sent back to you.

I am able to read an write to it using the fstream library. The problem is when I try to read from the buffer and nothing is there.

int main(int argc, char** argv)
{
fstream filestr;
filestr.open ("COM4", fstream::in | fstream::out | fstream::trunc);

if (!filestr.is_open())
{
    cout << "error opening port";
}
else
{
    cout << "port opened";
}

char* input = new char();
cin >> input;
filestr.write(input, 1);
filestr.flush();

char * buffer = new char [1];
buffer[0] = -1;

filestr.read (buffer,1);
while ((int)buffer[0] == -1)
{
    filestr.read (buffer,1);
}
cout << buffer[0];

cin >> input;

filestr.close();
return 0;  
}

So I send it some data and start reading in a loop until the arduino responds back. The very first read wont get anything back because the arduino hasn't had time to respond, so I keep reading until it does get data. But I seem to never get a response. It does work if I put a small delay before the first read and give the arduino time to respond. Does the position of the reader move forward when I read something? When I read something from the buffer does it automatically get deleted from the buffer? Anyone know how to do this?

Ricky Casavecchia
  • 560
  • 3
  • 9
  • 28

2 Answers2

0

You should grab the code of the arduino firmata windows tool. It does everything what you are trying to do.

http://firmata.org/wiki/Main_Page

Visual Micro
  • 1,561
  • 13
  • 26
0

Checkout this another question about using Boost Asio to read serial ports: Reading from serial port with Boost Asio

Community
  • 1
  • 1
oblitum
  • 11,380
  • 6
  • 54
  • 120