二:串口接收端程序
/***************************************************************************************************
**文件: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--板子间的。
