-
Notifications
You must be signed in to change notification settings - Fork 2
/
PosixSerial.cpp
92 lines (73 loc) · 1.82 KB
/
PosixSerial.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
/*
* Serial Communictaion in Posix standard
*/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "PosixSerial.h"
bool CPosixSerial::Open(const char* ttyS)
{
char text[256];
this->ttyS = ttyS;
portHandle = open(ttyS, O_RDWR | O_NOCTTY);
if (portHandle == -1) {
sprintf(text, "Could not open %s\nAlready in use?\n", ttyS);
MyMessageBox(text);
return false;
}
// configure port settings
tcgetattr(portHandle, &CommConfig);
// 2400 Baud / Data Size 8-Bit / 1 Stop Bit / No Parity / No Flow Control / Zero TimeOut
CommConfig.c_cflag = CREAD|CLOCAL|B2400|CS8;
CommConfig.c_lflag = 0;
CommConfig.c_oflag = 0;
CommConfig.c_iflag = 0; CommConfig.c_cc[VMIN] = 0;
CommConfig.c_cc[VTIME]= 0;
// Set DTR & RTS
ioctl(portHandle, TIOCMSET, TIOCM_DTR | TIOCM_RTS);
if (tcsetattr(portHandle, TCSAFLUSH, &CommConfig)) {
sprintf(text, "Could not write port settings on %s\n", ttyS);
MyMessageBox(text);
return false;
}
return true;
}
void CPosixSerial::Close(void)
{
close(portHandle);
}
void CPosixSerial::ClearBuffer(void)
{
}
int CPosixSerial::Read(char* data, unsigned int length)
{
int ret;
char text[256];
ret = read(portHandle, data, length);
if (ret == -1) {
sprintf(text, "Could not read from %s", ttyS);
MyMessageBox(text);
}
return ret;
}
int CPosixSerial::Write(char* data, unsigned int length)
{
int ret;
char text[256];
ret = write(portHandle, data, length);
if (ret == -1) {
sprintf(text, "Could not write to %s", ttyS);
MyMessageBox(text);
}
return ret;
}
void CPosixSerial::Timeout(unsigned int timeout) //msec
{
CommConfig.c_cc[VTIME]=timeout/100;
tcsetattr(portHandle, TCSAFLUSH, &CommConfig);
}
void CPosixSerial::MyMessageBox(char* text)
{
std::cout << text << std::endl;
}