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

📄 comport_old.c

📁 一个串口通讯的c语言的例子
💻 C
字号:
// 对串口的操作#define ETX  0x03#define STX  0x02// 获得当前时间long getCurrTime(){	long currTime; 	time( &currTime );    //printf( "Time in seconds since UTC 1/1/70:\t%ld\n", currTime );	return currTime;}//open a COM2 port :tty2aint openPort(char *dev){	int fd; /* File descriptor for the port */	fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);		if (fd == -1){	// Could not open the port.		printf("Unable to open %s port\n",dev);		return -1;	}//	printf("Opened a serial port: %s\n",dev);	return fd;}//close Portvoid closePort(int fd){	close(fd);}//read data from serial port and check data int readPort(int fd,unsigned char *buffer,int *length){	int	i = 0, n = 1, len = 0, flag = 0, timeout = 0;	unsigned char lrc = '\x00';					//unsigned char	lrc;	long currTime1,currTime2;//	printf("read begin .....\n");	if ( read(fd, buffer, 1) > 0 ) {			// 读启始位‘02’		if (buffer[0] == STX){			printf("[%02x]", buffer[0] );		}else{//			printf("Error Head!\n");			return 0;		}	}else{//		printf("No data!\n");		return 0;	}	currTime1=getCurrTime();		for ( ; ; ) {		if (read(fd, &buffer[n], 1) > 0 ) {			printf("[%02x]", buffer[n] );			fflush(stdout);			if ( flag < 2 ) {				len = len * 100 + (((buffer[n] & 0xf0) >> 4) * 10 + (buffer[n] & 0x0f));				lrc ^= buffer[n];                flag++;				n++;			}else if ( flag == 2 && i++ < len ){				*length = len + 5;				lrc ^= buffer[n];				n++;			}else if ( flag == 2 && i >= len ){				if ( buffer[n] == ETX ){					lrc ^ = buffer[n];					flag++;					n++;				} else {//					printf("\nETX not received\n" );					return( -1 );				}			}else if ( flag == 3 ){				if ( lrc != buffer[n] ) {//					printf("2 resp LRC: %2x, cacl LRC: %02x\n", buffer[n], lrc );					return( -2 );				} else {					return( len );				}			}		}else {//			printf("\nNot data\n" );			currTime2 = getCurrTime();//			printf("\ntime=%d-%d\n",currTime2,currTime1);			if( (currTime2-currTime1)>timeout){//				printf("\nTime out=%d\n", currTime2-currTime1);//				printf("\nTime out\n" );				return( 0 );			}		}	}}//write to serial portvoid writePort(int fd,unsigned char *buffer,int len){	int  k;	for ( k = 0; k < len; k++) {//		printf("[%02x]",buffer[k]);		while ( write(fd, buffer + k, 1) != 1 );	}}int setAttr(int fdread){	struct termio comtty;		if(ioctl(fdread,TCGETA,&comtty)){		printf("\n[ERROR]: Get tty error\n" );		return (-1);	}	comtty.c_iflag = 1;	comtty.c_oflag = 0;	comtty.c_cflag =(B9600|CS8|CREAD|HUPCL|CLOCAL);	comtty.c_lflag = 0;	comtty.c_cc[VMIN]=0;	comtty.c_cc[VTIME]=1;	if(ioctl(fdread,TCSETA,&comtty)==-1){		printf("\n[ERROR]: Set tty error\n" );		return (-1);	}}int setNowait(int fd){	struct termio term_attr;		if(fd<0) return -1;		if(ioctl(fd,TCGETA,&term_attr)<0)		return -1;		term_attr.c_cc[VMIN]=0;	term_attr.c_cc[VTIME]=1;		if(ioctl(fd,TCSETAW,&term_attr)<0)		return -1;		return 0;}

⌨️ 快捷键说明

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