ads1115 analog-to-digital 4-channel added
[i2c-telemetry.git] / pcf8591_4.c
1 #include <stdio.h>
2 #include <stdint.h>
3 #include <fcntl.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <linux/i2c-dev.h>
7 #include <linux/i2c.h>
8 #include <sys/ioctl.h>
9 #include "smbus.h"
10 #include <ncurses.h> /* sudo apt-get install libncurses5-dev */
11
12 // gcc -o pcf8591_2 -lncurses pcf8591_2.c
13
14 int main( int argc, char **argv )
15 {
16    int i;
17    int r;
18    int fd;
19    int aout;
20    unsigned char command[2];
21    unsigned char value[4];
22    unsigned char str[8];
23    useconds_t delay = 5000;
24
25    char *dev = "/dev/i2c-0";
26    int addr = 0x48;
27
28    int j;
29    int key;
30
31    initscr();
32    noecho();
33    cbreak();
34    nodelay(stdscr, true);
35    curs_set(0);
36    printw("PCF8591");
37
38    mvaddstr(10, 0, "Brightness");
39    mvaddstr(12, 0, "Temperature");
40    mvaddstr(14, 0, "?");
41    mvaddstr(16, 0, "Resistor");
42    refresh();
43    fd = open(dev, O_RDWR );
44    if(fd < 0)
45    {
46       perror("Opening i2c device node\n");
47       return 1;
48    }
49
50    r = ioctl(fd, I2C_SLAVE, addr);
51    if(r < 0)
52    {
53       perror("Selecting i2c device\n");
54    }
55
56    command[1] = 0;
57    aout = 0;
58    while(1)
59    {
60       for(i = 0; i < 4; i++)
61       {
62          command[1]=aout++;
63          command[0] = 0x40 | ((i + 1) & 0x03); // output enable | read input i
64          r = write(fd, &command, 2);
65          usleep(delay);
66          // the read is always one step behind the selected input
67          r = read(fd, &value[i], 1);
68          if(r != 1)
69          {
70             perror("reading i2c device\n");
71          }
72          usleep(delay);
73
74          sprintf(str, "%3d", value[i]);
75          mvaddstr(10+i+i, 12, str);
76          value[i] = value[i] / 4;
77          move(10 + i + i, 16);
78
79          for(j = 0; j < 64; j++)
80          {
81             if(j < value[i])
82             {
83                addch('*');
84             }
85             else
86             {
87                addch(' ');
88             }
89          }
90       }
91       refresh();
92
93       key = getch();
94       if(key == 43)
95       {
96          command[1]++;
97       }
98       else if(key == 45)
99       {
100          command[1]--;
101       }
102       else if(key > -1)
103       {
104          break;
105       }
106    }
107
108    endwin();
109    close(fd);
110    printf("%d\n", key);
111    return(0);
112 }