I've been able to connect to and get the Serial data from the Arduino. When I use, in my Ubuntu terminal, cu -l /dev/ttyUSB0 it prints the information correctly. When I run my c++ program no matter how I have managed to control the USB settings in the termios struct I get a whole mess of gibberish trying to print chars to the screen using something like:
cout << data << endl;
OR
(In a for loop)
cout << (char)data
;
cout << data;
printf("%s", data);
printf("%c", data);
I'm getting the same junk/gibberish chars. I guess it could be possible to have it run, write to a file then read that file but reading and writing at the same time would call for much greater difficulty requiring mutex locks to make sure I don't run into the end of the file.
I will paste the code I am using below if you care to have a look see:
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <stdio.h>
using namespace std;
#define bufferSize 100
int open_port(void)
{
int fd;
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY| O_NDELAY);
if (fd == -1)
{
// Could not open port so send error
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
{
// port is open and connected to fd
fcntl(fd, F_SETFL, 0); // if don't want to block use FNDELAY
return (fd);
}
return (fd);
}
int set_port(int fd)
{
struct termios options;
tcgetattr(fd, &options); // get current options for port
cfsetispeed(&options, B9600); // set input baud rate
cfsetospeed(&options, B9600); // set output baud rate
options.c_cflag |= (CLOCAL | CREAD); // enable receiver and set local mode
// No parity and 8 bit char definition with 1 stop bit
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
// options.c_cflag &= ~CRTSCTS; // Turn off flow of hardware control
return tcsetattr(fd, TCSANOW, &options);
}
int main() {
unsigned char data[bufferSize];
int fd = open_port();
set_port(fd);
while (read(fd, &data[0], sizeof(data)) != -1)
{
// cout << data << endl; // this prints the same gibberish as the for loop print statement.
int lastCheck = sizeof(data);
int i = 0;
for (i = 0; i < lastCheck; i++)
{
cout << data[i];
}
}
if (read(fd, &data[0], sizeof(data)) == -1)
{
cout << "Reached end of USB read" << endl;
}
return 0;
}