ads1115 analog-to-digital 4-channel added
[i2c-telemetry.git] / ads1115.c
1
2 #include <stdio.h>
3 #include <sys/types.h> // open
4 #include <sys/stat.h>  // open
5 #include <fcntl.h>     // open
6 #include <unistd.h>    // read/write usleep
7 #include <stdlib.h>    // exit
8 #include <inttypes.h>  // uint8_t, etc
9 #include <linux/i2c-dev.h> // I2C bus definitions
10
11 float getVin(int pin) {
12
13   int fd;
14   int ads_address = 0x48;
15
16   uint8_t buf[10];
17   int16_t val;
18   uint8_t pinCodes[4];
19
20   pinCodes[0]=0xc3;
21   pinCodes[1]=0xd3;
22   pinCodes[2]=0xe3;
23   pinCodes[3]=0xf3;
24
25   // open device on /dev/i2c-0
26   if ((fd = open("/dev/i2c-0", O_RDWR)) < 0) {
27     printf("Error: Couldn't open device! %d\n", fd);
28     return 1;
29   }
30
31   // connect to ads1115 as i2c slave
32   if (ioctl(fd, I2C_SLAVE, ads_address) < 0) {
33     printf("Error: Couldn't find device on address!\n");
34     return 1;
35   }
36      
37   // AIN0 and GND, 4.096v, 128s/s
38
39   buf[0] = 1;    // config register is 1
40   buf[1] = pinCodes[pin];
41   buf[2] = 0x85;
42   if (write(fd, buf, 3) != 3) {
43     perror("Write to register 1");
44     exit(-1);
45   }
46
47   usleep(10000);
48
49   // wait for conversion complete
50   do {
51     if (read(fd, buf, 2) != 2) {
52       perror("Read conversion");
53       exit(-1);
54     }
55   } while (buf[0] & 0x80 == 0);
56
57   // read conversion register
58   buf[0] = 0;   // conversion register is 0
59   if (write(fd, buf, 1) != 1) {
60     perror("Write register select");
61     exit(-1);
62   }
63   if (read(fd, buf, 2) != 2) {
64     perror("Read conversion");
65     exit(-1);
66   }
67
68   // convert output and display results
69   val = (int16_t)buf[0]*256 + (uint16_t)buf[1];
70   
71   close(fd);
72
73   return (float)val*4.096/32768.0;
74 }
75
76 main() {
77
78   int i;
79   for ( i=0; i<=3; i++) {
80     printf("Vin%1d (V) %5.3f\n",i,getVin(i));
81   }
82
83 }