ads1115 analog-to-digital 4-channel added
[i2c-telemetry.git] / pcf8591d.c
1 //***************************************************
2 // pcf8591d.c
3 // 
4 // Example to read A/D values from a 
5 // 4 channel / 8 bit AD converter PCF8591
6 // through I2C using the I2C driver improved by
7 // Geert Vancompernolle
8 // http://www.acmesystems.it/?id=10
9 //***************************************************
10
11 #include "stdio.h"
12 #include "stdlib.h"
13 #include "unistd.h"
14 #include "sys/ioctl.h"
15 #include "fcntl.h"
16 #include "time.h"
17 #include "string.h"
18
19 #include "i2c_errno.h"
20 #include "etraxi2c.h"
21
22
23 int main( int argc, char **argv ) {
24   int rtc;
25   int fd_i2c;
26   I2C_DATA i2c_d;
27   int ch;
28
29   printf("Reading from a PCF8591 (4 chanel A/D at 8 bits with I2C bus)\n");
30
31   fd_i2c = open( "/dev/i2c-0", O_RDWR );
32   if (fd_i2c<=0)     {
33     printf( "Open error on /dev/i2c\n" );
34     exit( 1 );
35   }
36
37   // PCF8591 address scheme
38   // |  1 |  0 |  0 |  1 | A2 | A1 | A0 | R/W |
39 //  i2c_d.slave =(0x09<<4)|(0x01<<1);
40
41   i2c_d.slave = 0x48;
42
43   for (ch=0;ch<=3;ch++) {
44     // Select the A/D channel
45     i2c_d.wbuf[0] = ch;
46     i2c_d.wlen  = 1;
47     if ((rtc=ioctl(fd_i2c,_IO( ETRAXI2C_IOCTYPE, I2C_WRITE), &i2c_d))!=EI2CNOERRORS)  {
48       close(fd_i2c);
49       printf( "Error %d on line %d\n",rtc,__LINE__);
50       return ( -1 );
51     }
52
53     i2c_d.rlen  = 3;
54     if ((rtc=ioctl(fd_i2c,_IO( ETRAXI2C_IOCTYPE, I2C_READ), &i2c_d))!=EI2CNOERRORS)  {
55       close(fd_i2c);
56       printf( "Error %d on line %d\n",rtc,__LINE__);
57       return ( -1 );
58     }
59
60     // Show the voltage level
61     printf("Chanel %d = %.2fv (%02X hex)\n",ch,i2c_d.rbuf[2]*0.012941,i2c_d.rbuf[2]);
62   }
63
64   close(fd_i2c);
65   return(0);
66 }
67