-
Notifications
You must be signed in to change notification settings - Fork 1
/
SCSerial.cpp
146 lines (129 loc) · 2.76 KB
/
SCSerial.cpp
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/*
* SCSerial.h
* 飞特串行舵机硬件接口层程序
* 日期: 2022.3.29
* 作者:
*/
#include "SCSerial.h"
SCSerial::SCSerial()
{
IOTimeOut = 100;
fd = -1;
txBufLen = 0;
}
SCSerial::SCSerial(u8 End):SCS(End)
{
IOTimeOut = 100;
fd = -1;
txBufLen = 0;
}
SCSerial::SCSerial(u8 End, u8 Level):SCS(End, Level)
{
IOTimeOut = 100;
fd = -1;
txBufLen = 0;
}
bool SCSerial::begin(int baudRate, const char* serialPort)
{
if(fd != -1){
close(fd);
fd = -1;
}
//printf("servo port:%s\n", serialPort);
if(serialPort == NULL)
return false;
fd = open(serialPort, O_RDWR | O_NOCTTY | O_NONBLOCK);
if(fd == -1){
perror("open:");
return false;
}
fcntl(fd, F_SETFL, FNDELAY);
tcgetattr(fd, &orgopt);
tcgetattr(fd, &curopt);
speed_t CR_BAUDRATE = baudRate;
cfsetispeed(&curopt, CR_BAUDRATE);
cfsetospeed(&curopt, CR_BAUDRATE);
printf("serial speed %d\n", baudRate);
//Mostly 8N1
curopt.c_cflag &= ~PARENB;
curopt.c_cflag &= ~CSTOPB;
curopt.c_cflag &= ~CSIZE;
curopt.c_cflag |= CS8;
curopt.c_cflag |= CREAD;
curopt.c_cflag |= CLOCAL;//disable modem statuc check
cfmakeraw(&curopt);//make raw mode
curopt.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
if(tcsetattr(fd, TCSANOW, &curopt) == 0){
return true;
}else{
perror("tcsetattr:");
return false;
}
}
int SCSerial::setBaudRate(int baudRate)
{
if(fd==-1){
return -1;
}
tcgetattr(fd, &orgopt);
tcgetattr(fd, &curopt);
speed_t CR_BAUDRATE = baudRate;
cfsetispeed(&curopt, CR_BAUDRATE);
cfsetospeed(&curopt, CR_BAUDRATE);
return 1;
}
int SCSerial::readSCS(unsigned char *nDat, int nLen)
{
int fs_sel;
fd_set fs_read;
int rvLen = 0;
struct timeval time;
FD_ZERO(&fs_read);
FD_SET(fd,&fs_read);
time.tv_sec = 0;
time.tv_usec = IOTimeOut*1000;
//使用select实现串口的多路通信
while(1){
fs_sel = select(fd+1, &fs_read, NULL, NULL, &time);
if(fs_sel){
rvLen += read(fd, nDat+rvLen, nLen-rvLen);
//printf("nLen = %d rvLen = %d\n", nLen, rvLen);
if(rvLen<nLen){
continue;
}else{
return rvLen;
}
}else{
//printf("serial read fd read return 0\n");
return rvLen;
}
}
}
int SCSerial::writeSCS(unsigned char *nDat, int nLen)
{
while(nLen--){
txBuf[txBufLen++] = *nDat++;
}
return txBufLen;
}
int SCSerial::writeSCS(unsigned char bDat)
{
txBuf[txBufLen++] = bDat;
return txBufLen;
}
void SCSerial::rFlushSCS()
{
tcflush(fd, TCIFLUSH);
}
void SCSerial::wFlushSCS()
{
if(txBufLen){
txBufLen = write(fd, txBuf, txBufLen);
txBufLen = 0;
}
}
void SCSerial::end()
{
fd = -1;
close(fd);
}