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

📄 ttyrcv.c

📁 linux 串口 接收程序
💻 C
字号:
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */  

#define TRUE 1 

int main() 
{
	int fd, res=0; 
	struct termios oldtio, newtio; 
	char buf[10]; 

/*
*open serial port1
*/
	fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
	if (fd == -1)
		perror("open_port: Unable to open /dev/ttyS1.");
	else
		fcntl(fd, F_SETFL, 0);

	tcgetattr(fd, &oldtio);  //store oldtio
	bzero(&newtio, sizeof(newtio));  //set null newtio
/*
* Set the baud rates to 38400
*/
	cfsetispeed(&newtio, B38400);
	cfsetospeed(&newtio, B38400);
/*
* Enable the receiver and set local mode
*/
	newtio.c_cflag |= (CLOCAL | CREAD);
/*
* Set the new options for the port
*/
	newtio.c_cflag &= ~PARENB;
	newtio.c_cflag &= ~CSTOPB;
	newtio.c_cflag &= ~CSIZE; 
	newtio.c_cflag |= CS8; 

	newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);  //set raw input mode

	newtio.c_iflag |= (INPCK | ISTRIP); //check and strip parity bit

	newtio.c_iflag &= ~(IXON | IXOFF | IXANY);  //no flow control
 
	newtio.c_oflag &= ~OPOST; //set raw output mode

//	newtio.c_cc[VMIN] = 0;
//	newtio.c_cc[VTIME] = 10;

//	tcflush(fd,TCIOFLUSH);

	tcsetattr(fd, TCSANOW, &newtio);

	while (TRUE) {     /* 回圈会在我们发出终止的讯号後跳出 */ 
 /* 即使输入超过 255 个字元, 读取的程式段还是会一直等到行终结符出现才停止. 
    如果读到的字元组低於正确存在的字元组, 则所剩的字元会在下一次读取时取得. 
    res 用来存放真正读到的字元组个数 */ 
		res = read(fd, buf, 10);  
		buf[res]=0;             /* 设定字串终止字元, 所以我们能用 printf */ 
		if(res>0)
		{
			printf("%s\n", buf); 
		}
		if (buf[0]=='z') break; 
	}

/* 回存旧的序列埠设定值 */ 
	tcsetattr(fd, TCSANOW, &oldtio); 
	close(fd);
	return 0;
}

⌨️ 快捷键说明

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