-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiygeiger.c
52 lines (40 loc) · 981 Bytes
/
diygeiger.c
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
#include "diygeiger.h"
int diy_open(const char *device, speed_t baud) {
int fd = -1;
struct termios tio;
memset(&tio, 0, sizeof(struct termios));
tio.c_cflag = CS8 | CREAD | CLOCAL; // 8n1
tio.c_cc[VMIN] = 0;
tio.c_cc[VTIME] = 5;
if ((fd = open(device, O_RDWR)) != -1) {
if (cfsetspeed(&tio, baud) == 0) // usually 9600 baud
if (tcsetattr(fd, TCSANOW, &tio) == 0)
// Return file descriptor,
return fd;
// ... otherwise close device.
close(fd);
fd = -1;
}
return fd;
}
void diy_close(int device) {
close(device);
}
int diy_get_cpm(int device) {
char buf[13] = { 0 };
// Arduino sends 10-digit decimal number (unsigned long) plus tailing "\r\n".
diy_read(device, buf, 12);
return atoi(buf);
}
int diy_read(int device, char *buf, unsigned int len) {
unsigned int n;
ssize_t rcvd = 0;
char *inp = &buf[0];
for (n = 0; n < len; n++) {
rcvd += read(device, inp, 1);
inp = &buf[rcvd];
if (rcvd >= len)
break;
}
return rcvd;
}