你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux下的串口编程

[日期:2012-12-20] 来源:Linux社区   作者:huangminqiang [字体:大 中 小]

二:串口接收端程序

/***************************************************************************************************
**文件:r_uart.c
**编写者:huangminqiang
**编写日期:2012年10月15号
**简要描述:串口接收程序,在板子上运行。
**修改者:
**修改日期:2012年11月12号
**注:
****************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#define COM "/dev/ttyAMA0"

/****** 读取串口信息 *********************************************************************************/
int ReadUartInfo(void)
{
int fd;
int cnt = 0;
int r_cnt = 0;
struct termios attr;
fd_set r_fds;
struct timeval tv;
unsigned char r_buf[128] = {0};

//打开串口
fd = open(COM, O_RDWR);
if(0 > fd)
{
perror("open uart error : ");
return -1;
}

//由于串口设置已固化,故不需要设置。
#if 0
//设置串口参数
if ( set_com(fd, B115200, CS8, NON, 1) )
{
printf("set_com failed!\n");
goto _out;
}
#endif

while(1)
{
//清除监测集合
FD_ZERO(&r_fds);
//将串口句柄加入到监测集合中
FD_SET(fd, &r_fds);

//设置超时为3秒
tv.tv_sec = 3;
tv.tv_usec = 0;

//监测串口是否有数据接收到,超时为3秒
cnt = select(fd + 1, &r_fds, NULL, NULL, &tv);
switch(cnt)
{
case 0://超时
//printf("time out !\n");
break;
case -1://错误
perror("select : ");
goto _out;

default:
if( FD_ISSET(fd, &r_fds) ) //有数据可读
{
//接收数据
r_cnt = read(fd, r_buf, sizeof (r_buf));
if(0 > r_cnt)
{
perror("read error : ");
goto _out;
}
//printf("%s", r_buf);
//system(r_buf);
}
}

memset(r_buf, 0, sizeof(r_buf));
}

// 关闭串口
close(fd);
return 0;
_out:
close(fd);
return -1;
}


/****** 主函数 ***************************************************************************************/
int main(void)
{
if( ReadUartInfo() )
{
printf("read uart data failed!\n");
return -1;
}

return 0;
}

 

因为PC机上的串口设置已经固化,所以,没必要再配置了,串口的收发程序主要用于板子(新)上的,而上面的主要用于测试PC--板子间的。

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款