UartConnection.c 2.7 KB
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <sys/time.h> 

#include "JZsdkLib.h"

/*******************************************
*
*   使能一个串口 返回设备号
*   变量1   串口设备名
	变量2  比特率
	返回 int 设备号
	例子: UartDeal_Base_CreateReceive("/dev/ttyS2", 115200)

*******************************************/
int UartConnection_UartEnabled(char *UartDev, int BitRate)
{
    int ret = 0;
    int UartReceive_fd = 0;
	pthread_t UartReceive_task;
    char PrintStr[256];

	//1、读取串口
	UartReceive_fd = open(UartDev,O_RDWR);
	if(UartReceive_fd < 0)
	{
        snprintf(PrintStr, 256, "打开%s失败", UartDev);
		printf("%s\n", PrintStr);
		return -1;
	}
	else
	{
		snprintf(PrintStr, 256, "打开%s成功", UartDev);
		printf("%s\n", PrintStr);
	}
	
	//2、获取终端信息
	struct  termios options;
	if(tcgetattr(UartReceive_fd,&options)!= 0)									//获取终端信息
	{
		printf("获取终端信息失败!\n");
		return -1;
	}		

	//3、设置比特率
	switch (BitRate)
	{
        case 115200:
            cfsetispeed(&options, B115200);
            cfsetospeed(&options, B115200);
            break;
        case 230400:
            cfsetispeed(&options, B230400);
            cfsetospeed(&options, B230400);
            break;
        case 460800:
            cfsetispeed(&options, B460800);
            cfsetospeed(&options, B460800);
            break;
        case 921600:
            cfsetispeed(&options, B921600);
            cfsetospeed(&options, B921600);
            break;
        case 1000000:
            cfsetispeed(&options, B1000000);
            cfsetospeed(&options, B1000000);
            break;
		default:
			return -1;
			break;
	}

    options.c_cflag |= (unsigned) CLOCAL;
    options.c_cflag |= (unsigned) CREAD;
    options.c_cflag &= ~(unsigned) CRTSCTS;
    options.c_cflag &= ~(unsigned) CSIZE;
    options.c_cflag |= (unsigned) CS8;
    options.c_cflag &= ~(unsigned) PARENB;
    options.c_iflag &= ~(unsigned) INPCK;
    options.c_cflag &= ~(unsigned) CSTOPB;
    options.c_oflag &= ~(unsigned) OPOST;
    options.c_lflag &= ~((unsigned) ICANON | (unsigned) ECHO | (unsigned) ECHOE | (unsigned) ISIG);
    options.c_iflag &= ~((unsigned) BRKINT | (unsigned) ICRNL | (unsigned) INPCK | (unsigned) ISTRIP | (unsigned) IXON);
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 0;
	
	
	tcflush(UartReceive_fd,TCIOFLUSH);										//刷清输入、输出队列
	tcsetattr(UartReceive_fd,TCSAFLUSH,&options);									//串口设置使能
	
	return UartReceive_fd;
}