Hello,
I'm trying to communicate with my arduino through the posix serial library.
It kind of works but the first line is distorted.
It should print "flamingo:" in the console
but most of the time I get stuff like
flamflamingo
or
fflamingo
that's for the first line
the other lines seem to work well.
I've seen this happening in the arduino serial monitor too but only on rare occasions...
Here is the code I'm using
#include <stdio.h> /* Standard input/output definitions */
#include <stdlib.h>
#include <stdint.h> /* Standard types */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/ioctl.h>
#include <getopt.h>
int serialport_init(void);
int main()
{
int fd = 0;
char buf[256];
int n;
int i;
char b[1];
int wloopc=0;
fd = serialport_init();
while(wloopc<1){
i=0;
while( b[0]!='\n' ) {
n = read(fd, b, 1); // read a char at a time
if( n==-1) break; // couldn't read
if( n==0 ) {
usleep( 10 * 1000 ); // wait 10 msec try again
continue;
}
buf[i]=b[0];
i++;
}
buf[i]=0; // 0 terminate the string
fputs(buf,stdout);
b[0]=0; // reset b[0] so while loop can start over
}
}
int serialport_init(void)
{
struct termios toptions;
int fd;
int baud=B9600;
//fprintf(stderr,"init_serialport: opening port %s @ %d bps\n",
// serialport,baud);
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("init_serialport: Unable to open port ");
return -1;
}
if (tcgetattr(fd, &toptions) < 0) {
perror("init_serialport: Couldn't get term attributes");
return -1;
}
speed_t brate = baud; // let you override switch below if needed
brate=baud;
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
// 8N1
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
// no flow control
toptions.c_cflag &= ~CRTSCTS;
toptions.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
toptions.c_oflag &= ~OPOST; // make raw
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 20;
if( tcsetattr(fd, TCSAFLUSH, &toptions) < 0) { //Was TCSANOW
perror("init_serialport: Couldn't set term attributes");
return -1;
}
return fd;
}
Any ideas?