UartConnection.c
2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#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;
}