chiark / gitweb /
Debian build: Fix .so symlinks
[wiringPi.git] / wiringPi / pcf8591.c
1 /*
2  * pcf8591.c:
3  *      Extend wiringPi with the PCF8591 I2C GPIO Analog expander chip
4  *      The chip has 1 8-bit DAC and 4 x 8-bit ADCs
5  *      Copyright (c) 2013 Gordon Henderson
6  ***********************************************************************
7  * This file is part of wiringPi:
8  *      https://projects.drogon.net/raspberry-pi/wiringpi/
9  *
10  *    wiringPi is free software: you can redistribute it and/or modify
11  *    it under the terms of the GNU Lesser General Public License as
12  *    published by the Free Software Foundation, either version 3 of the
13  *    License, or (at your option) any later version.
14  *
15  *    wiringPi is distributed in the hope that it will be useful,
16  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *    GNU Lesser General Public License for more details.
19  *
20  *    You should have received a copy of the GNU Lesser General Public
21  *    License along with wiringPi.
22  *    If not, see <http://www.gnu.org/licenses/>.
23  ***********************************************************************
24  */
25
26 #include <unistd.h>
27
28 #include "wiringPi.h"
29 #include "wiringPiI2C.h"
30
31 #include "pcf8591.h"
32
33
34 /*
35  * myAnalogWrite:
36  *********************************************************************************
37  */
38
39 static void myAnalogWrite (struct wiringPiNodeStruct *node, int pin, int value)
40 {
41   unsigned char b [2] ;
42   b [0] = 0x40 ;
43   b [1] = value & 0xFF ;
44   write (node->fd, b, 2) ;
45 }
46
47
48 /*
49  * myAnalogRead:
50  *********************************************************************************
51  */
52
53 static int myAnalogRead (struct wiringPiNodeStruct *node, int pin)
54 {
55   int x ;
56
57   wiringPiI2CWrite (node->fd, 0x40 | ((pin - node->pinBase) & 3)) ;
58
59   x = wiringPiI2CRead (node->fd) ;      // Throw away the first read
60   x = wiringPiI2CRead (node->fd) ;
61
62   return x ;
63 }
64
65
66 /*
67  * pcf8591Setup:
68  *      Create a new instance of a PCF8591 I2C GPIO interface. We know it
69  *      has 4 pins, (4 analog inputs and 1 analog output which we'll shadow
70  *      input 0) so all we need to know here is the I2C address and the
71  *      user-defined pin base.
72  *********************************************************************************
73  */
74
75 int pcf8591Setup (const int pinBase, const int i2cAddress)
76 {
77   int fd ;
78   struct wiringPiNodeStruct *node ;
79
80   if ((fd = wiringPiI2CSetup (i2cAddress)) < 0)
81     return fd ;
82
83   node = wiringPiNewNode (pinBase, 4) ;
84
85   node->fd          = fd ;
86   node->analogRead  = myAnalogRead ;
87   node->analogWrite = myAnalogWrite ;
88
89   return 0 ;
90 }