chiark / gitweb /
Properly added the max31855 files now
[wiringPi.git] / wiringPi / max31855.c
1 /*
2  * max31855.c:
3  *      Extend wiringPi with the max31855 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 "max31855.h"
29
30 /*
31  * myAnalogRead:
32  *      Return the analog value of the given pin
33  *      Note: The chip really only has one read "channel", but we're faking it
34  *      here so we can read the error registers. Channel 0 will be the data
35  *      channel, and 1 is the error register code.
36  *      Note: Temperature returned is temp in C * 4, so divide result by 4
37  *********************************************************************************
38  */
39
40 static int myAnalogRead (struct wiringPiNodeStruct *node, int pin)
41 {
42   unsigned int spiData ;
43   int temp ;
44   int chan = pin - node->pinBase ;
45
46   wiringPiSPIDataRW (node->fd, (unsigned char *)&spiData, 4) ;
47
48   if (chan == 0)                        // Read temp in C
49   {
50     spiData >>= 18 ;
51     temp = spiData & 0x3FFF ;           // Bottom 13 bits
52     if ((spiData & 0x2000) != 0)        // Negative
53       temp = -temp ;
54     return temp ;
55   }
56   else                                  // Return error bits
57     return spiData & 0x7 ;
58 }
59
60
61 /*
62  * max31855Setup:
63  *      Create a new wiringPi device node for an max31855 on the Pi's
64  *      SPI interface.
65  *********************************************************************************
66  */
67
68 int max31855Setup (const int pinBase, int spiChannel)
69 {
70   struct wiringPiNodeStruct *node ;
71
72   if (wiringPiSPISetup (spiChannel, 5000000) < 0)       // 5MHz - prob 4 on the Pi
73     return -1 ;
74
75   node = wiringPiNewNode (pinBase, 2) ;
76
77   node->fd         = spiChannel ;
78   node->analogRead = myAnalogRead ;
79
80   return 0 ;
81 }