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

📄 uarttest.c

📁 串口检测程序
💻 C
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <termios.h>#include <fcntl.h>#include <sys/types.h>typedef unsigned char u8;typedef unsigned int u32;int speed_arr[] =  { B9600, B19200, B57600, B115200, B500000, B1000000, B2000000 };int name_arr[] = { 9600, 19200, 57600, 115200, 500000, 1000000, 2000000 };char *dev_name[] = { "/dev/ttyS0", "/dev/ttyS1", "/dev/ttyS2", "/dev/ttyS3" };voidsetspeed (int fd, int speed){  int i;  int status;  printf ("set baudrate:%d\n", speed);  struct termios opt;  tcgetattr (fd, &opt);  for (i = 0; i < sizeof (speed_arr) / sizeof (int); i++)    {      if (speed == name_arr[i])	{	  tcflush (fd, TCIOFLUSH);	  cfsetispeed (&opt, speed_arr[i]);	  cfsetospeed (&opt, speed_arr[i]);	  status = tcsetattr (fd, TCSANOW, &opt);	  if (status != 0)	  {  perror ("tcsetattr fd");	  return;}	}      tcflush (fd, TCIOFLUSH);    }}				//set speed of uartintmain (int argc, char *argv[]){  int fd, rt;  int w=0;  int n_read, n_write;  int i, n = 0;  int speed = 0;		//baudrate  u8 w_buf[100];  char r_buf[100];    char *dev={0};    for(i=0;i<8;i++)    {    	w_buf[i]=i+1;    }  //read baudrate  while ((rt = getopt (argc, argv, "hwb:c:")) >= 0)    switch (rt)      {      case 'h':	printf ("Usage:%s [-h] [-w] [-b] [baudrate] [-c] [/dev/ttyS*] \n"		"\t-b set the uart baudrate!\n"		"\t-w write the uart before read it!\n"		"\t-c the uart NO.", argv[0]);	return 0;      case 'b':	speed = atoi (optarg);	printf ("get baudrate:%d\n", speed);	break;      case 'w':	w=1;        break;      case 'c':	dev = dev_name[atoi (optarg)];	break;      }  //open uart  if ((fd = open (dev, O_RDWR | O_NONBLOCK)) == -1)    {      perror ("open uart:");      return 0;    }  if (!speed)    {      printf ("error:set baudrate first\n");      return 0;    }  //set this uart baudrate  setspeed (fd, speed);  //init uart  struct termios options;  if ((tcgetattr (fd, &options)) != 0)    {      printf ("tcgetattr failed!");      return 1;    }  printf ("get cflag:%08x\n", options.c_cflag);//  options.c_cflag |= (CLOCAL | CREAD);  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);  options.c_iflag &= ~(IXON | IXOFF | IXANY);  options.c_oflag &= ~OPOST;//  options.c_oflag &= ~CRTSCTS;//  options.c_cflag &= ~ CSTOPB;//  options.c_cflag &= ~PARENB;  tcsetattr (fd, TCSANOW, &options);  //read and write uart  while (1)    {      if (w)	n_write = write (fd, w_buf, 8);      if ((n_read = read (fd, r_buf, 8)) > 0)         {		  for (i = 0; i < n_read; i++)	    {	      printf ("%02x ", r_buf[i]);	      n++;	      if (n == 8)		{		  printf ("\n");		  n = 0;		}	    }         }       	    }  close (fd);}

⌨️ 快捷键说明

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