-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserial_communication.cpp
93 lines (71 loc) · 1.95 KB
/
serial_communication.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
#include "serial_communication.h"
Serial::Serial()
{
}
Serial::~Serial()
{
}
bool Serial::Open(const char* port_name)
{
struct termios options;
memset(&options, 0, sizeof(options));
int status;
if((m_fd = open(port_name, O_RDWR | O_NDELAY | O_NONBLOCK)) == -1)
{
// printf("error %d opening %s: %s", errno, port_name, strerror(errno));
return false;
}
fcntl(m_fd, F_SETFL, O_RDWR);
if(tcgetattr(m_fd, &options) != 0)
{
// printf("error %d from tcgetattr", errno);
return false;
}
cfmakeraw(&options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD); //ignore modem controls,
options.c_cflag &= ~PARENB; //shut off parity
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 0; //read doesn't block
options.c_cc[VTIME] = 100; //10 seconds read timeout
if(tcsetattr(m_fd, TCSANOW, &options) != 0)
{
// printf("error %d from tcsetattr", errno);
return false;
}
ioctl(m_fd, TIOCMGET, &status);
status |= TIOCM_DTR;
status |= TIOCM_RTS;
ioctl(m_fd, TIOCMSET, &status);
usleep(2000000); //2s
// set_blocking(m_fd, 0); //set no blocking
return true;
}
void Serial::Close()
{
close(m_fd);
}
void Serial::Write(const byte message[5])
{
// byte *data;
// strcpy(data, message);
// strcat(data, '\n');
// int data_length = sizeof(message);
write(m_fd, message, 5); //send message
usleep((5 + 25) * 100); //sleep enough to transmit the message
}
char* Serial::Read(int buffer_length)
{
if(buffer_length < 1)
{
return "";
}
char message[buffer_length];
int n = read(m_fd, message, sizeof(message)); //read up to 100 characters if ready to read
return message;
}