ads1115 analog-to-digital 4-channel added
[i2c-telemetry.git] / pcf8591_2.c
1 /*
2     PCF8591_addr_line.c
3     -------------------
4     read the voltage on one A/D line (0-3) and set the output voltage on the D/A pin
5     --------------------------------------------------------------------------------
6
7       1) send the i2c address as decimal
8       2) send A/D line number (program adds 64 to enable D/A in control register)
9       3) send byte for D/A out
10       4) read the chosen A/D - print it as a raw decimal 0 to 255
11       5) save the chosen port value to /var/www/ramdisk/AtoD.dat
12   usage :-  type with spaces but without the < >
13 <PCF8591_address_readvolts>  <address as decimal> <A/D line 0-3> <D/A value as decimal 0-255>
14       (even if the D/A pin is unused type in any value 0-255)
15 */
16
17 #include <stdio.h>
18 #include <stdint.h>
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <linux/i2c-dev.h>
23 #include <linux/i2c.h>
24 #include <sys/ioctl.h>
25 #include "smbus.h"
26
27
28 int main(int argc, char** argv)
29 {
30   int i2c; 
31   int AD_line;      /* line number 0-3 */
32   int V_out;        /* value for the D/A out line */
33   int buf[1];       /* use to feed the i2c driver */
34   int address;      /* i2c bus address */
35   int byte_in_0;    /* the 8 bit byte that represents the voltage on the AD_line */
36
37  if (argc != 4)   /* report error if we are not getting just 3 inputs after the program name */
38  {
39   printf("Error. usage: %s i2c_chip_address A/D_line_(0-3) D/A_Vout(0-255)\n", argv[0]);
40  }
41
42   address = atoi(argv[1]); /* address is the first number after the program name */
43   AD_line = atoi(argv[2]); /* A/D input line 0-3 */
44   AD_line = AD_line + 64;  /* enable the D/A output pin */
45   V_out = atoi(argv[3]); /* A/D input line 0-3 */
46
47   i2c = open("/dev/i2c/0",O_RDWR); /* open the i2c-bus number 0 */
48
49   ioctl(i2c,I2C_SLAVE, address); /* set the i2c-bus address of the chip we will talk to */
50
51   buf[0] = AD_line;       /* A/D input line number is the first data byte sent */
52   buf[1] = V_out;         /* D/A out value is the second data byte sent */
53
54   write(i2c,buf,2); /* we send 2 bytes <control register> <D/A value> */
55
56   read(i2c,buf,1);  /* buf(0) contains the byte of data in the chip cache */
57   /* do it again */
58   read(i2c,buf,1);  /* buf(0) now contains the byte of data from the most recent analogue input*/
59
60   printf("BYTE = %d \n", buf[0]);
61   printf("%d\n", buf[0]);
62   /* buf[0] is an integer. It goes 0 to 255 as voltage input goes from 0 to supply voltage*/
63
64   //save AtoD byte to ramdisk
65   FILE *f;
66   f = fopen("/tmp/AtoD.dat","w");
67   fprintf(f, "%d", buf[0]);
68   fclose(f);
69
70   i2c = close(i2c);
71 }
72
73