⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serial.c

📁 嵌入式Linux应用系统开发实例精讲源代码
💻 C
字号:
/*	serial.c by bitzilla@gmail.com		*/ #include "serial.h"int init_serial(char* dev)	{	int fd=open(dev,O_RDWR);	if(fd<0)	{		printf("cannot open %s\n",dev);		exit(-1);	}	else		printf("%s open successfully.\n",dev);	return fd;}void set_speed(int fd,int speed)	{	int i,status;	struct termios opt;	tcgetattr(fd,&opt);	for(i=0;i<sizeof(speed_arr)/sizeof(int);i++)	{		if(speed == name_arr[i])	{			tcflush(fd,TCIOFLUSH);/*TCIOFLUSH   						flushes both data received but not read, and  data  written  but              					not transmitted.*/			cfsetispeed(&opt,speed_arr[i]);/*设置串口输入速度*/			cfsetospeed(&opt,speed_arr[i]);/*设置串口输出速度*/			status = tcsetattr(fd,TCSANOW,&opt);	/*设置设备工作模式*/			if(status != 0)	perror("tcsetattr fd error!");			break;		}		tcflush(fd,TCIOFLUSH);	}}int set_parity(int fd,int databits,int stopbits,int parity)	{	/**	 *@brief   设置串口数据位,停止位和效验位	 *@param  fd     类型  int  打开的串口文件句柄	 *@param  databits 类型  int 数据位   取值 为 7 或者8	 *@param  stopbits 类型  int 停止位   取值为 1 或者2	 *@param  parity  类型  int  效验类型 取值为N,E,O,,S	 */	struct termios opt;	if(tcgetattr(fd,&opt) != 0)	{	/*得到设备当前模式*/		perror("setup serial...");		return 0;	}	/* 设置数据位数前,首先使用‘CSIZE’屏蔽数据位数 */	opt.c_cflag &= ~CSIZE;		/*CSIZE  Character size mask.  Values are CS5, CS6, CS7, or CS8.*/	switch(databits)	{	/*设置数据位数*/	case 7:		opt.c_cflag |= CS7;	/*设置数据位数=7*/		break;	case 8:		opt.c_cflag |= CS8;	/*设置数据位数=8*/		break;	default:		printf("unsupport data size.\n");		return 0;	}		switch(parity)	{	/*设置串口校验位*/	case 'n':	case 'N':		opt.c_cflag &= ~PARENB;	/*set the PARENB bit to zero-------disable parity checked*/		opt.c_iflag &= ~INPCK;	/*set the INPCK bit to zero--------INPCK means inparitycheck(not paritychecked)*/		break;	case 'o':	case 'O':		opt.c_cflag |= (PARENB|PARODD);		opt.c_iflag |= INPCK;		break;	case 'e':	case 'E':		opt.c_cflag |= PARENB;		opt.c_cflag &= ~PARODD;		opt.c_iflag |= INPCK;  		break;	case 's':	case 'S':		opt.c_cflag &= ~PARENB;		opt.c_cflag &= ~CSTOPB;	/*CSTOPB---Set two stop bits, rather than one.*/		break;	default:		printf("unsupported parity.\n");		return 0;	}		switch(stopbits)	{	/*设置停止位*/		case 1:			opt.c_cflag &= ~CSTOPB;			break;		case 2:			opt.c_cflag &= CSTOPB;			break;		default:			printf("unsupported stopbits.\n");			return 0;	}		if(parity !='n')	opt.c_iflag |= INPCK;	tcflush(fd,TCIFLUSH);	opt.c_cc[VTIME] = 150;	opt.c_cc[VMIN] = 0;		if(tcsetattr(fd,TCSANOW,&opt) != 0)	{		perror("\n");		return 0;	}	return 1;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -