serial.c

来自「The source code example of ARM9 developm」· C语言 代码 · 共 76 行

C
76
字号
/* *	Description:  *		serial port example *		matrix P1 set 19200bps, n81, RTS/CTS flow control. and echo back the received data. * *		What is shown in this example: *		1. How to open a serial port *		2. How to set interface *		3. How to set baudrate, flow control and other settings *		4. How to read and write a serial port *		 */#include <stdio.h>#include <termios.h>#include <errno.h>#include <fcntl.h>#include "matrix500.h"intmain(argc, argv)	int	argc;	char	*argv[];{	int	fd, interface, ret;	char	buf[1024];	struct termios T_new;	/*open tty port*/	fd = open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY);	if (fd == -1) {		printf("open /dev/ttyS0 Failed, errno: %d\r\n", errno);		return 0;	}	/*set serial interface: RS-232*/	interface = UC500_UART_TYPE_232;	if(ioctl(fd, UC500_SET_UART_TYPE, &interface) != 0) {		printf("set UART type: %d...Failed, errno: %d\r\n", interface, errno);		close(fd);		return 0;	}	/*termios functions use to control asynchronous communications ports*/        if (tcgetattr(fd, &T_new) != 0) {	/*fetch tty state*/		printf("tcgetattr failed. errno: %d\r\n", errno);		close(fd);		return 0;         }	/*set 	19200bps, n81, RTS/CTS flow control, 		ignore modem status lines, 		hang up on last close, 		and disable other flags*/        T_new.c_cflag = (B19200 | CS8 | CREAD | CLOCAL | HUPCL | CRTSCTS); 	        T_new.c_oflag = 0;        T_new.c_iflag = 0;        T_new.c_lflag = 0;        if (tcsetattr(fd, TCSANOW, &T_new) != 0) {		printf("tcsetattr failed. errno: %d\r\n", errno);		close(fd);		return 0;         }	while(1) {		/*when data received, send them back*/		ret = read(fd, buf, sizeof(buf));		if (ret > 0) {			write(fd, buf, ret);		}	}	return 0;}

⌨️ 快捷键说明

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