-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSerialPort.cpp
More file actions
95 lines (80 loc) · 2.07 KB
/
SerialPort.cpp
File metadata and controls
95 lines (80 loc) · 2.07 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
#include "../Headers/SerialPort.h"
SerialPort::SerialPort()
{
this->connected = false;
this->handler = INVALID_HANDLE_VALUE;
}
SerialPort::~SerialPort() { closeSerialPort(); }
void SerialPort::openSerialPort(const char *portName, const int baudRate)
{
this->connected = false;
this->handler =
CreateFileA(static_cast<LPCSTR>(portName), GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (this->handler != INVALID_HANDLE_VALUE)
{
DCB dcbSerialParameters = {0};
if (!GetCommState(this->handler, &dcbSerialParameters))
{
printf("failed to get current serial parameters");
}
else
{
dcbSerialParameters.BaudRate = baudRate;
dcbSerialParameters.ByteSize = 8;
dcbSerialParameters.StopBits = ONESTOPBIT;
dcbSerialParameters.Parity = NOPARITY;
dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE;
if (!SetCommState(handler, &dcbSerialParameters))
{
printf("ALERT: could not set Serial port parameters\n");
}
else
{
this->connected = true;
PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR);
}
}
}
}
void SerialPort::closeSerialPort()
{
this->connected = false;
CloseHandle(this->handler);
}
int SerialPort::readSerialPort(char *buffer, unsigned int buf_size)
{
DWORD bytesRead;
unsigned int toRead = 0;
ClearCommError(this->handler, &this->errors, &this->status);
if (this->status.cbInQue > 0)
{
if (this->status.cbInQue > buf_size)
{
toRead = buf_size;
}
else
{
toRead = this->status.cbInQue;
}
}
if (ReadFile(this->handler, buffer, toRead, &bytesRead, NULL))
{
return bytesRead;
}
return 0;
}
bool SerialPort::writeSerialPort(char *buffer, unsigned int buf_size)
{
DWORD bytesSend;
if (!WriteFile(this->handler, (void *)buffer, buf_size, &bytesSend, 0))
{
ClearCommError(this->handler, &this->errors, &this->status);
return false;
}
else
{
return true;
}
}
bool SerialPort::isConnected() { return this->connected; }