Statistics
| Branch: | Revision:

ddr4s / fw / wiringPi / wiringPi / mcp3004.c @ 32:cadb9025f1e0

History | View | Annotate | Download (2.17 KB)

1
/*
2
 * mcp3004.c:
3
 *        Extend wiringPi with the MCP3004 SPI Analog to Digital convertor
4
 *        Copyright (c) 2012-2013 Gordon Henderson
5
 *
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/
10
 *
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.
15
 *
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.
20
 *
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
 ***********************************************************************
25
 */
26

    
27
#include <wiringPi.h>
28
#include <wiringPiSPI.h>
29

    
30
#include "mcp3004.h"
31

    
32
/*
33
 * myAnalogRead:
34
 *        Return the analog value of the given pin
35
 *********************************************************************************
36
 */
37

    
38
static int myAnalogRead (struct wiringPiNodeStruct *node, int pin)
39
{
40
  unsigned char spiData [3] ;
41
  unsigned char chanBits ;
42
  int chan = pin - node->pinBase ;
43

    
44
  chanBits = 0b10000000 | (chan << 4) ;
45

    
46
  spiData [0] = 1 ;                // Start bit
47
  spiData [1] = chanBits ;
48
  spiData [2] = 0 ;
49

    
50
  wiringPiSPIDataRW (node->fd, spiData, 3) ;
51

    
52
  return ((spiData [1] << 8) | spiData [2]) & 0x3FF ;
53
}
54

    
55

    
56
/*
57
 * mcp3004Setup:
58
 *        Create a new wiringPi device node for an mcp3004 on the Pi's
59
 *        SPI interface.
60
 *********************************************************************************
61
 */
62

    
63
int mcp3004Setup (const int pinBase, int spiChannel)
64
{
65
  struct wiringPiNodeStruct *node ;
66

    
67
  if (wiringPiSPISetup (spiChannel, 1000000) < 0)
68
    return FALSE ;
69

    
70
  node = wiringPiNewNode (pinBase, 8) ;
71

    
72
  node->fd         = spiChannel ;
73
  node->analogRead = myAnalogRead ;
74

    
75
  return TRUE ;
76
}