chiark / gitweb /
More typos, added mcp3004/mcp3008
[wiringPi.git] / wiringPi / mcp3004.c
1 /*
2  * mcp3004.c:
3  *      Extend wiringPi with the MCP3004 SPI Analog to Digital convertor
4  *      Copyright (c) 2012-2013 Gordon Henderson
5  ***********************************************************************
6  * This file is part of wiringPi:
7  *      https://projects.drogon.net/raspberry-pi/wiringpi/
8  *
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.
13  *
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.
18  *
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  ***********************************************************************
23  */
24
25 #include <wiringPi.h>
26 #include <wiringPiSPI.h>
27
28 #include "mcp3004.h"
29
30 /*
31  * myAnalogRead:
32  *      Return the analog value of the given pin
33  *********************************************************************************
34  */
35
36 static int myAnalogRead (struct wiringPiNodeStruct *node, int pin)
37 {
38   unsigned char spiData [2] ;
39   unsigned char chanBits ;
40   int chan = pin - node->pinBase ;
41
42   chanBits = 0b11000000 | (chan << 3) ;
43
44   spiData [0] = chanBits ;
45   spiData [1] = 0 ;
46
47   wiringPiSPIDataRW (node->fd, spiData, 2) ;
48
49   return ((spiData [0] << 7) | (spiData [1] >> 1)) & 0x3FF ;
50 }
51
52
53 /*
54  * mcp3004Setup:
55  *      Create a new wiringPi device node for an mcp3004 on the Pi's
56  *      SPI interface.
57  *********************************************************************************
58  */
59
60 int mcp3004Setup (const int pinBase, int spiChannel)
61 {
62   struct wiringPiNodeStruct *node ;
63
64   if (wiringPiSPISetup (spiChannel, 1000000) < 0)
65     return -1 ;
66
67   node = wiringPiNewNode (pinBase, 8) ;
68
69   node->fd         = spiChannel ;
70   node->analogRead = myAnalogRead ;
71
72   return 0 ;
73 }