Linux 串口编程

1 代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>

int Uart_Init(char *Device, unsigned int Baudrate)
{
	int fd;
	int res;
	struct termios config;
	
	fd = open(Device, O_RDWR|O_NOCTTY|O_NDELAY);
	
	//打开失败
	if(fd == -1){
		return fd;
	}

	//配置串口
	bzero(&config, sizeof(config));		
	config.c_cflag |= (CLOCAL|CREAD);		// 使能读
	config.c_cflag &= ~CSIZE;			
	config.c_cflag |= CS8;					// 8位数据
	config.c_cflag &= ~PARENB;				// 无校验
	config.c_cflag &= ~CSTOPB;				// 停止位为1
	config.c_cc[VTIME] = 0;					
	config.c_cc[VMIN]  = 0;
	cfsetispeed (&config, Baudrate);			//输入波特率
	cfsetospeed (&config, Baudrate);			//输出波特率


	res = tcsetattr(fd, TCSANOW, &config);
	if(res != 0){
		close (fd);
		return -2;
	}
	
	return fd;
}

void main()
{
	int fd;
	int i,j;
	int res;
	
	char buf[1024]="Hello Serial";
	int len;

	fd = Uart_Init("/dev/ttyS3", B115200);

	len = strlen(buf);
	
	res = write (fd, buf, len);
	printf("write size=%d\n", res);
	
	
	sleep(1);
	buf[0] = '\0';
	res = read(fd, buf, len);
	printf("read  size=%d %s\n", res, buf);

	close(fd);
}

2 参考链接

一、串口编程流程

https://blog.csdn.net/baweiyaoji/article/details/72885633

https://blog.csdn.net/u011192270/article/details/48174353

二、termios介绍

https://www.cnblogs.com/einstein-2014731/p/6922977.html

posted @ 2022-10-01 11:50  立秋了  阅读(38)  评论(0编辑  收藏  举报