forked from glidernet/diy-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.h
95 lines (71 loc) · 2.47 KB
/
serial.h
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 <unistd.h>
#include <fcntl.h>
#include <termios.h>
class SerialPort
{ public:
int DeviceHandle;
public:
SerialPort()
{ DeviceHandle=(-1); }
~SerialPort()
{ Close(); }
int isOpen(void) const { return DeviceHandle>=0; }
int Open(const char *DeviceName="/dev/ttyS0", int BaudRate=9600)
{ Close();
DeviceHandle=open(DeviceName, O_RDWR | O_NOCTTY | O_NDELAY );
if(DeviceHandle<0) return -1;
int Speed; // speed_t Speed;
if(BaudRate==4800) Speed=B4800;
else if(BaudRate==9600) Speed=B9600;
else if(BaudRate==19200) Speed=B19200;
else if(BaudRate==38400) Speed=B38400;
else if(BaudRate==57600) Speed=B57600;
else if(BaudRate==115200) Speed=B115200;
else if(BaudRate==230400) Speed=B230400;
// else if(BaudRate==128000) Speed=B128000;
// else if(BaudRate==256000) Speed=B256000;
else return -2;
struct termios Options;
tcgetattr(DeviceHandle, &Options);
if(cfsetispeed(&Options, Speed)<0) return -2;
if(cfsetospeed(&Options, Speed)<0) return -2;
// cfsetspeed(&Options, Speed);
Options.c_cflag |= (CLOCAL | CREAD);
Options.c_cflag &= ~PARENB; // 8-bits, no parity
Options.c_cflag &= ~CSTOPB;
Options.c_cflag &= ~CSIZE;
Options.c_cflag |= CS8;
Options.c_cc[VTIME] = 0;
Options.c_cc[VMIN] = 1;
tcsetattr(DeviceHandle, TCSANOW, &Options);
/*
int Bytes=sizeof(Options);
uint8_t *Ptr = (uint8_t *)(&Options);
printf("Options[%d] =", Bytes);
for( ; Bytes; Bytes--, Ptr++)
{ printf(" %02X", *Ptr); }
printf("\n");
*/
return 0; }
int OpenFileForRead(const char *FileName)
{ Close();
DeviceHandle=open(FileName, O_RDONLY);
if(DeviceHandle<0) return -1;
return 0; }
int Close(void)
{ if(DeviceHandle>=0)
{ close(DeviceHandle); DeviceHandle=(-1); }
return 0; }
int Read(char *Buffer, size_t MaxChars)
{ int Len=read(DeviceHandle, Buffer, MaxChars);
return Len<=0 ? 0:Len; }
int Read(char &Char)
{ return Read(&Char, 1); }
int Write(char *Buffer, size_t Chars)
{ int Len=write(DeviceHandle, Buffer, Chars);
return Len<=0 ? 0:Len; }
int Write(char *String)
{ return Write(String, strlen(String)); }
int Write(char Char)
{ return Write(&Char,1); }
} ;