linux下串口编程设置函数---------set_opt(fd1,115200,8,'N'1)--------------------

简介: <p>open /dev/ttys0, 设备文件之后,得到文件描述符, 对串口进行设置。</p> <p></p> <pre code_snippet_id="261621" snippet_file_name="blog_20140328_1_1409127" name="code" class="objc">/***串口设置函数:例(fd1, 115200, 8, 'N', 1);

open /dev/ttys0, 设备文件之后,得到文件描述符, 对串口进行设置。

/**
*串口设置函数:例(fd1, 115200, 8, 'N', 1);
*参数:
*fd:串口设备节点
*nSpeed:波特率
*nBits:数据位
*nEvent:校验位
*nStop:停止位
*返回值:成功 -- 0
*		 失败 -- -1
*/
int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop)
{
	struct termios newtio,oldtio;
	if  ( tcgetattr( fd,&oldtio)  !=  0) { 
		perror("SetupSerial 1");
		return -1;
	}
	bzero( &newtio, sizeof( newtio ) );
	newtio.c_cflag  |=  CLOCAL | CREAD;
	newtio.c_cflag &= ~CSIZE;

	switch( nBits )
	{
	case 7:
		newtio.c_cflag |= CS7;
		break;
	case 8:
		newtio.c_cflag |= CS8;
		break;
	}

	switch( nEvent )
	{
	case 'O':
		newtio.c_cflag |= PARENB;
		newtio.c_cflag |= PARODD;
		newtio.c_iflag |= (INPCK | ISTRIP);
		break;
	case 'E': 
		newtio.c_iflag |= (INPCK | ISTRIP);
		newtio.c_cflag |= PARENB;
		newtio.c_cflag &= ~PARODD;
		break;
	case 'N':  
		newtio.c_cflag &= ~PARENB;
		break;
	}

	switch( nSpeed )
	{
	case 2400:
		cfsetispeed(&newtio, B2400);
		cfsetospeed(&newtio, B2400);
		break;
	case 4800:
		cfsetispeed(&newtio, B4800);
		cfsetospeed(&newtio, B4800);
		break;
	case 9600:
		cfsetispeed(&newtio, B9600);
		cfsetospeed(&newtio, B9600);
		break;
	case 115200:
		cfsetispeed(&newtio, B115200);
		cfsetospeed(&newtio, B115200);
		break;
	case 460800:
		cfsetispeed(&newtio, B460800);
		cfsetospeed(&newtio, B460800);
		break;
	default:
		cfsetispeed(&newtio, B9600);
		cfsetospeed(&newtio, B9600);
		break;
	}
	if( nStop == 1 )
		newtio.c_cflag &=  ~CSTOPB;
	else if ( nStop == 2 )
	newtio.c_cflag |=  CSTOPB;
	newtio.c_cc[VTIME]  = 0;
	newtio.c_cc[VMIN] = 0;
	tcflush(fd,TCIFLUSH);
	if((tcsetattr(fd,TCSANOW,&newtio))!=0)
	{
		perror("com set error");
		return -1;
	}
//	printf("set done!\n\r");
	return 0;
}


目录
相关文章
|
17天前
|
Linux
关于Linux目录访问函数总结
关于Linux目录访问函数总结
13 1
|
24天前
|
存储 算法 Linux
【Linux系统编程】Linux 文件系统探究:深入理解 struct dirent、DIR 和 struct stat结构
【Linux系统编程】Linux 文件系统探究:深入理解 struct dirent、DIR 和 struct stat结构
36 0
|
7天前
|
Linux 数据安全/隐私保护
Linux设置PPPOE
请注意,以上步骤是基本的设置流程。具体步骤可能会因Linux发行版和版本的不同而有所差异,确保按照你所使用的系统来进行设置。如果使用图形界面,也可以在网络设置中配置PPPoE连接。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
19 0
|
10天前
|
安全 Unix Linux
一、linux 常用命令之 linux版本信息 系统管理与设置 持续更新******
一、linux 常用命令之 linux版本信息 系统管理与设置 持续更新******
14 0
|
11天前
|
Linux 开发者
Linux文件编程(open read write close函数)
通过这些函数,开发者可以在Linux环境下进行文件的读取、写入和管理。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
84 4
|
17天前
|
安全 Linux
嵌入式Linux系统关闭串口调试信息的输出
嵌入式Linux系统关闭串口调试信息的输出
13 1
|
17天前
|
传感器 Linux API
嵌入式Linux串口编程简介
嵌入式Linux串口编程简介
15 1
|
18天前
|
Linux 测试技术 C语言
【Linux】应用编程之C语言文件操作
【Linux】应用编程之C语言文件操作
|
24天前
|
存储 Unix Linux
深入理解 Linux 系统下的关键网络接口和函数,gethostent,getaddrinfo,getnameinfo
深入理解 Linux 系统下的关键网络接口和函数,gethostent,getaddrinfo,getnameinfo
14 0
|
25天前
|
存储 自然语言处理 C++
map和set的简单介绍
map和set的简单介绍
20 1