xiehui006 发表于 2014-06-03 16:36

关于Linux串口读取数据丢失的问题

在arm开发板上写的一个读取串口数据的程序,发现每次读的时候会把第一个字节丢失。

例如,我在windows下用串口工具发:abcdef
板子上收到的数据是:bcdef,它把第一个a丢掉了。这是什么原因?

代码:

#include <stdio.h>
#include <unistd.h> /*Unix标准函数定义*/
#include <sys/types.h> /**/
#include <sys/stat.h> /**/
#include <fcntl.h> /*文件控制定义*/
#include <termios.h> /*PPSIX终端控制定义*/
#include <errno.h> /*错误号定义*/
#include <stdlib.h>
#include <string.h>

int main()
{
        int fd,readnum;
        char *dev="/dev/ttyS0",recv;
        struct termios opt,oldopt;

        fd = open( dev, O_RDWR );
        if(fd == -1)
        {
                printf("open ttyS0 error!");
                perror("ttyS0:");
                return 0;
        }
       
        printf("open ttyS0 success!");

        tcgetattr( fd,&oldopt);

        tcgetattr( fd,&opt);
        cfsetispeed(&opt, B115200);//9600
        cfsetospeed(&opt, B115200);

        opt.c_cflag &= ~PARENB; //N
        opt.c_cflag &= ~INPCK;
        opt.c_cflag &= ~CSTOPB;//1
        opt.c_cflag &= ~CSIZE;
        opt.c_cflag |= CS8; //8

        opt.c_iflag &= ~(IXON | IXOFF | IXANY);

        opt.c_cc = 0;
        opt.c_cc = 0;

        opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/
        opt.c_oflag &= ~OPOST; /*Output*/

        tcflush(fd, TCIOFLUSH);
        tcsetattr(fd, TCSANOW, &opt);

        while(1)
        {
                bzero(recv,100);
                while((readnum = read(fd,recv,100))>0)
                {
                        printf("%s\n",recv);
                }
        }

        tcflush(fd, TCIOFLUSH);
        tcsetattr(fd, TCSANOW, &oldopt);
        close(fd);
}
页: [1]
查看完整版本: 关于Linux串口读取数据丢失的问题