Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage data from serial port

Tags:

c

linux

I wrote a code in Linux platform that read the data in serial port, my code below:

int fd;
char *rbuff=NULL;
struct termios new_opt, old_opt;
int ret;

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
if( fd == -1 )
{
   printf("Can't open file: %s\n", strerror(errno));
   return -1;
}
tcgetattr(fd, &old_opt);
new_opt.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
new_opt.c_iflag = IGNPAR /*| ICRNL*/;
new_opt.c_oflag = 0;
new_opt.c_lflag = ICANON;

tcsetattr(fd, TCSANOW, &new_opt);
rbuff = malloc(NBUFF);
printf("reading..\n");
memset(rbuff,0x00,NBUFF);
ret = read(fd, rbuff, NBUFF);
printf("value:%s",rbuff);
if(ret == -1)
{
   printf("Read error:%s\n",strerror(errno));
   return -1;
}
tcsetattr(fd, TCSANOW, &old_opt);
close(fd);

My problem is the code above doesn't read the first data that was transmitted, then the second transmission the data is garbage, then the third is the normal data.

Did I missed a setting in the serial port?

Thanks.

like image 947
domlao Avatar asked Nov 15 '22 10:11

domlao


1 Answers

Sounds like your serial port settings are off - at a guess, you are reading in 8 bits instead of 7. You have to have both sides transmitting with the same settings.

What I would do is have a table of "bytes expected, bytes gotten", and run it for some 5-6 trials.

Next, if that doesn't help you, crank the baud on both sides down to 2400 or so. Yes, I'm serious. That can fix some oddball errors.

You should investigate getting your hands on an oscilloscope. If you anticipate this to be something you're maintaining in the long-term, an o-scope can be quite handy.

like image 126
Paul Nathan Avatar answered Nov 16 '22 23:11

Paul Nathan