-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
76 lines (57 loc) · 1.68 KB
/
main.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
// The PiWeather board i2c address
#define ADDRESS 0x04
// The I2C bus: This is for V2 pi's. For V1 Model B you need i2c-0
static const char *devName = "/dev/i2c-1";
int main(int argc, char** argv) {
if (argc == 1) {
printf("Supply one or more commands to send to the Arduino\n");
exit(1);
}
// printf("I2C: Connecting\n");
int file;
if ((file = open(devName, O_RDWR)) < 0) {
fprintf(stderr, "I2C: Failed to access %s\n", devName);
exit(1);
}
// printf("I2C: acquiring buss to 0x%x\n", ADDRESS);
if (ioctl(file, I2C_SLAVE, ADDRESS) < 0) {
fprintf(stderr, "I2C: Failed to acquire bus access/talk to slave 0x%x\n", ADDRESS);
exit(1);
}
int arg;
for (arg = 1; arg < argc; arg++) {
int val;
unsigned char cmd[16];
if (0 == sscanf(argv[arg], "%d", &val)) {
fprintf(stderr, "Invalid parameter %d \"%s\"\n", arg, argv[arg]);
exit(1);
}
// printf("Sending %d\n", val);
cmd[0] = val;
if (write(file, cmd, 1) == 1) {
// As we are not talking to direct hardware but a microcontroller we
// need to wait a short while so that it can respond.
//
// 1ms seems to be enough but it depends on what workload it has
usleep(10000);
char buf[1];
if (read(file, buf, 1) == 1) {
int temp = (int) buf[0];
printf("%0.1f\n", temp+0.0);
}
}
// Now wait else you could crash the arduino by sending requests too fast
usleep(10000);
}
close(file);
return (EXIT_SUCCESS);
}