lin下串口通信程序

内核编译和嵌入式产品的设计与开发
回复
xyaya
帖子: 21
注册时间: 2007-03-04 10:55

lin下串口通信程序

#1

帖子 xyaya »

程序如下:
#include <stdio.h> /*标准输入输出定义*/
#include <stdlib.h> /*标准函数库定义*/
#include <unistd.h> /*Unix 标准函数定义*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> /*文件控制定义*/
#include <termios.h> /*PPSIX 终端控制定义*/
#include <errno.h> /*错误号定义*/
#define FALSE -1
#define TRUE 0
/***打开串口***/
int OpenDev(char *Dev)
{
int fd = open(Dev,O_RDWR|O_NOCTTY|O_NDELAY);
if (-1==fd)
{
perror("Can't Open Serial Port\n");
return -1;
}
else
return fd;
}
/***设置速率***/
void set_speed(int fd, int speed)
{
struct termios opt;
tcgetattr(fd,&opt);
cfsetispeed(&opt,speed);
cfsetospeed(&opt,speed);
if(tcsetattr(fd,TCSANOW,&opt)!=0)
{
perror("tcsetattr error");
exit(0);
}
tcflush(fd,TCIOFLUSH);
}
/***设置串口数据位,停止位和效验位
* fd 类型 int 打开的串口文件句柄*
* databits 类型 int 数据位 取值 为 8*
* stopbits 类型 int 停止位 取值为 1*
* parity 类型 int 效验类型 取值为N(E,O,,S)***/
int set_Parity(int fd)
{
struct termios options;
//设置数据位
options.c_cflag&=~CSIZE;
//设置停止位
options.c_cflag&=~CSTOPB; //使用1个停止位
//8个数据位
options.c_cflag|=CS8;
//使用原始模式(Raw Mode)方式来通讯
options.c_lflag&=~(ICANON|ECHO|ECHOE|ISIG); /*Input*/
options.c_oflag&=~OPOST; /*Output*/
//设置校验位
options.c_cflag&=~PARENB; /* Clear parity enable */
options.c_iflag&=~INPCK; /* Enable parity checking */
options.c_cflag|=(CLOCAL|CREAD);
options.c_cflag&=CRTSCTS; //硬件流控制,即RTS/CTS硬件握手
options.c_cc[VTIME]=0;
options.c_cc[VMIN]= 1; /*没接收到一个字符后立即读数*/
tcflush(fd,TCIFLUSH);
printf("configure complete\n");
if(tcsetattr(fd,TCSANOW,&options)!=0)
{
perror("serial error!");
return FALSE;
}
}
int main(int argc, char **argv)
{
int fd;
int nread;
char buff[256];
char *dev ="/dev/ttyS0";
fd=OpenDev(dev);
if (fd>0)
set_speed(fd,B9600);
else
{
printf("Can't Open Serial Port!\n");
exit(0);
}
if (set_Parity(fd)== FALSE)
{
printf("Set Parity Error\n");
exit(0);
}
printf("start send and receive data\n");
{
//sleep(5000);
nread = read(fd,buff,256);
{
printf("\nreceive data from serical com %d\n",nread);
buff[nread+1]='\0';
printf("\n%s",buff);
}
}
close(fd);
return 0;
}
在root和一个普通用户名下执行,均出现:
configure complete
start send and receive data

receive data from serical com -1

思考不得解!求助。
ps:我的机子上ttyS0设备所属用户是root,所属用户组是dialout。系统是ubuntu
ben
帖子: 9
注册时间: 2005-07-31 10:01

#2

帖子 ben »

设置了非阻塞模式NDELAY的缘故吧
回复