3 * Extend wiringPi with the MCP3004 SPI Analog to Digital convertor
4 * Copyright (c) 2012-2013 Gordon Henderson
6 * Thanks also to "ShorTie" on IRC for some remote debugging help!
7 ***********************************************************************
8 * This file is part of wiringPi:
9 * https://projects.drogon.net/raspberry-pi/wiringpi/
11 * wiringPi is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as
13 * published by the Free Software Foundation, either version 3 of the
14 * License, or (at your option) any later version.
16 * wiringPi is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with wiringPi.
23 * If not, see <http://www.gnu.org/licenses/>.
24 ***********************************************************************
28 #include <wiringPiSPI.h>
34 * Return the analog value of the given pin
35 *********************************************************************************
38 static int myAnalogRead (struct wiringPiNodeStruct *node, int pin)
40 unsigned char spiData [3] ;
41 unsigned char chanBits ;
42 int chan = pin - node->pinBase ;
44 chanBits = 0b10000000 | (chan << 4) ;
46 spiData [0] = 1 ; // Start bit
47 spiData [1] = chanBits ;
50 wiringPiSPIDataRW (node->fd, spiData, 3) ;
52 return ((spiData [1] << 8) | spiData [2]) & 0x3FF ;
58 * Create a new wiringPi device node for an mcp3004 on the Pi's
60 *********************************************************************************
63 int mcp3004Setup (const int pinBase, int spiChannel)
65 struct wiringPiNodeStruct *node ;
67 if (wiringPiSPISetup (spiChannel, 1000000) < 0)
70 node = wiringPiNewNode (pinBase, 8) ;
72 node->fd = spiChannel ;
73 node->analogRead = myAnalogRead ;