免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2030 | 回复: 0
打印 上一主题 下一主题

[Linux] 关于Linux串口读取数据丢失的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-06-03 16:36 |只看该作者 |倒序浏览
在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[100];
        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[VTIME] = 0;
        opt.c_cc[VMIN] = 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);
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP