3 * Extend wiringPi with the MCP 23008 I2C GPIO expander chip
4 * Copyright (c) 2013 Gordon Henderson
5 ***********************************************************************
6 * This file is part of wiringPi:
7 * https://projects.drogon.net/raspberry-pi/wiringpi/
9 * wiringPi is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
14 * wiringPi is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with wiringPi.
21 * If not, see <http://www.gnu.org/licenses/>.
22 ***********************************************************************
29 #include "wiringPiI2C.h"
30 #include "mcp23x0817.h"
37 *********************************************************************************
40 static void myPinMode (struct wiringPiNodeStruct *node, int pin, int mode)
44 reg = MCP23x08_IODIR ;
45 mask = 1 << (pin - node->pinBase) ;
46 old = wiringPiI2CReadReg8 (node->fd, reg) ;
53 wiringPiI2CWriteReg8 (node->fd, reg, old) ;
59 *********************************************************************************
62 static void myPullUpDnControl (struct wiringPiNodeStruct *node, int pin, int mode)
67 mask = 1 << (pin - node->pinBase) ;
69 old = wiringPiI2CReadReg8 (node->fd, reg) ;
76 wiringPiI2CWriteReg8 (node->fd, reg, old) ;
82 *********************************************************************************
85 static void myDigitalWrite (struct wiringPiNodeStruct *node, int pin, int value)
89 bit = 1 << ((pin - node->pinBase) & 7) ;
97 wiringPiI2CWriteReg8 (node->fd, MCP23x08_GPIO, old) ;
104 *********************************************************************************
107 static int myDigitalRead (struct wiringPiNodeStruct *node, int pin)
111 mask = 1 << ((pin - node->pinBase) & 7) ;
112 value = wiringPiI2CReadReg8 (node->fd, MCP23x08_GPIO) ;
114 if ((value & mask) == 0)
123 * Create a new instance of an MCP23008 I2C GPIO interface. We know it
124 * has 8 pins, so all we need to know here is the I2C address and the
125 * user-defined pin base.
126 *********************************************************************************
129 int mcp23008Setup (const int pinBase, const int i2cAddress)
132 struct wiringPiNodeStruct *node ;
134 if ((fd = wiringPiI2CSetup (i2cAddress)) < 0)
137 wiringPiI2CWriteReg8 (fd, MCP23x08_IOCON, IOCON_INIT) ;
139 node = wiringPiNewNode (pinBase, 8) ;
142 node->pinMode = myPinMode ;
143 node->pullUpDnControl = myPullUpDnControl ;
144 node->digitalRead = myDigitalRead ;
145 node->digitalWrite = myDigitalWrite ;
146 node->data2 = wiringPiI2CReadReg8 (fd, MCP23x08_OLAT) ;