I'm writing a program in Xcode that will both read and write to a serial port device (Arduino Microcontroller). I know how to do this on a windows computer, but I'm not getting the same results from Xcode. Here is my Code:
I am successfully able to send a character at a time to my Arduino. The problem is in reading the echo that is sent back to the computer. I think the problem is that in the time it takes for the character to get to the Arduino, get processed and sent back, the computer has already attempted to read what is on the serial port. Here is an example of my output:
****************************
program started
fd: 3
New output Val: d
Out: d In:
New output Val: d
Out: d In: d
New output Val: f
Out: f In: d
New output Val: f
Out: f In: f
New output Val: x
Out: x In: f
program terminated
********************************
Any help I can get would be appreciated,
Stanton
Code:
#include <iostream>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int main(int argc, const char * argv[]) {
cout << "program started" << endl;
int fd;
fd = open("/dev/tty.usbmodem1421", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) cout << "Error Opening Port" << endl;
else cout << "fd: " << fd << endl;
struct termios options;
tcgetattr(fd,&options);
cfsetispeed(&options,B115200);
cfsetospeed(&options,B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
tcsetattr(fd,TCSANOW,&options);
char *outToArduino = new char[255];
char *inFromArduino = new char[255];
do {
cout << "\nNew output Val: "; cin >> outToArduino;
cout << "Out: " << outToArduino << "\t";
write(fd, outToArduino, 1);
// Arduino Echos back the same character
// that was sent to it.
read(fd, inFromArduino, 1);
cout << "In: " << inFromArduino << endl;
} while (outToArduino[0] != 'x');
cout << "program terminated" << endl;
close(fd);
return 0;
}
I am successfully able to send a character at a time to my Arduino. The problem is in reading the echo that is sent back to the computer. I think the problem is that in the time it takes for the character to get to the Arduino, get processed and sent back, the computer has already attempted to read what is on the serial port. Here is an example of my output:
****************************
program started
fd: 3
New output Val: d
Out: d In:
New output Val: d
Out: d In: d
New output Val: f
Out: f In: d
New output Val: f
Out: f In: f
New output Val: x
Out: x In: f
program terminated
********************************
Any help I can get would be appreciated,
Stanton