comtest.c

来自「Linux 串口编程(经过验证的代码) 强烈推荐」· C语言 代码 · 共 119 行

C
119
字号
/* ************************************************************
 *
 *  comTest.c -- linux serial port test procedure source
 *
 *  author: mark wang
 *  
 *  written: 2008/05/22
 *
 *  e-mail: markwang001@163.com
 *
 * ************************************************************ */
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <fcntl.h>

#include <errno.h>

#include <sys/io.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <termio.h>

#include <time.h>

#include <signal.h>



void stopKey(int fd)

{

	char c;

	while(1)

	{

		scanf("%c",&c);

		if(c=='0')

		{

			close(fd);

			break;

		}

	}

	exit(0);	

}



int main(int argc, char *argv[])

{

	int fd;

	char buf[256];

	int pre;

	pthread_t id;



	struct termios opt, newOpt;

	int ret;

	int status;

	int nread,nwrite;





	if(argc!=2)

	{

		printf("usage: %s devName\n", argv[0]);

		printf("examp: %s /dev/ttyS0\n", argv[0]);

		return(1);

	}

	

	if((fd=open(argv[1], O_RDWR|O_NOCTTY/*|O_NDELAY*/))<0)

	{

		perror("Error opening the port\n");

	}

	else

	{

		printf("Succeed opening the port with fd = %d\n",fd);

	}



	tcgetattr(fd, &opt);

	tcgetattr(fd, &newOpt);



	newOpt.c_cflag |= (CLOCAL | CREAD);

	newOpt.c_cflag &= ~CBAUD;

	newOpt.c_cflag |= (B115200 | CS8); 



        newOpt.c_lflag &= ~(ICANON | ISIG | NOFLSH);

	

	newOpt.c_lflag &= ~(ECHO);

	

	newOpt.c_lflag &= ~(ECHOE);

	



	newOpt.c_oflag &= ~(OPOST | ONLCR | OCRNL);



        newOpt.c_cc[VMIN]=100;

	newOpt.c_cc[VTIME]=2;

	

	tcflush(fd,TCIFLUSH);

	

	ret = tcsetattr(fd, TCSANOW, &newOpt);

	if(ret<0)

	{

		perror("Error when tesetattr serial port\n");

		exit(1);

	}
	



	pre = pthread_create(&id,NULL,(void *)stopKey,fd);



	if(pre!=0)

	{

		perror("Error creating the stopKey pthread\n");

		exit(1);

	}



	while(1)

	{

                nread=0;

                nwrite=0;

		bzero(buf,sizeof(buf));

		nread = read(fd, buf, 255);

		printf(":::::: %d bytes received\n", nread);

                buf[nread]='\0';

                printf("%s\n",buf);

		nwrite = write(fd, buf, nread);

		printf("|||||| %d bytes sended\n", nwrite);

	}

	close(fd);

}

⌨️ 快捷键说明

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