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

📄 serial.c

📁 本人写的linux下云台控制程序
💻 C
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <termios.h>struct tcspeed{	unsigned long baud;	speed_t code;};static struct tcspeed tcspeeds[] = {        {50, B50},        {75, B75},        {110, B110},        {134, B134},        {150, B150},        {200, B200},        {300, B300},        {600, B600},        {1200, B1200},        {1800, B1800},        {2400, B2400},        {4800, B4800},        {9600, B9600},        {19200, B19200},        {38400, B38400},        {57600, B57600},        {115200, B115200},        {230400, B230400},        {460800, B460800},        {921600, B921600},        {0, B0},//        {0, 0}};    int initial_serial(char* ttyS,int baudrate,int databits,char parity,int stopbits){	//default value:	// ttyS = /dev/ttyS0; 	//baudrate = 9600; databits = 8; parity = 0; stopbits = 1;		int fd,status,i,speed;	struct termios Opt;		//1.Open Serial Port	if(ttyS == NULL)	{		fprintf(stderr,"error: no device!\n");		return -1;	}	if(strncmp(ttyS,"/dev/ttyS",9))	{		fprintf(stderr,"error: Invalid device!\n");		return -1;	}	fd = open(ttyS,O_WRONLY | O_NDELAY | O_NOCTTY);	if(fd == -1)	{		fprintf(stderr,"Can`t Open Serial Port\n");		return -1;	}//	printf("Open Serial Port Successfully\n");			//2. Set Speed		for ( i= 0;  i < sizeof(tcspeeds) / sizeof(struct tcspeed);  i++)	{		if  (speed == tcspeeds[i].baud)		{			tcgetattr(fd,&Opt);			tcflush(fd, TCIOFLUSH);			cfsetispeed(&Opt,tcspeeds[i].code);			cfsetospeed(&Opt,tcspeeds[i].code);			status = tcsetattr(fd, TCSANOW, &Opt);			if  (status != 0)			{				perror("tcsetattr speed");				return -2;			}//			printf("Set Speed Successfully\n");			break;		}	}	//3. Set databits,parity and stopbits	if(tcgetattr(fd,&Opt) != 0)	{		perror("tcgetattr");		return -3;	}	Opt.c_cflag &= ~PARENB;	Opt.c_cflag &= ~CSTOPB;	Opt.c_cflag &= ~CSIZE;	Opt.c_cflag |= CS8;	Opt.c_oflag &= ~OPOST;	tcflush(fd,TCIFLUSH);	if(tcsetattr(fd,TCSANOW,&Opt) != 0)	{		perror("tcsetattr 8N1");		return -3;	}//	printf("Set 8N1 Successfully\n");//	fprintf(stderr,"open serial seccuss!\n"); //delete by edgarliu		return fd;}int close_serial(int fd){	close(fd);	return 0;}	    

⌨️ 快捷键说明

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