mcp3002.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * mcp3002.c:
  3. * Extend wiringPi with the MCP3002 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. #include <wiringPi.h>
  25. #include <wiringPiSPI.h>
  26. #include "mcp3002.h"
  27. /*
  28. * myAnalogRead:
  29. * Return the analog value of the given pin
  30. *********************************************************************************
  31. */
  32. static int myAnalogRead (struct wiringPiNodeStruct *node, int pin)
  33. {
  34. unsigned char spiData [2] ;
  35. unsigned char chanBits ;
  36. int chan = pin - node->pinBase ;
  37. if (chan == 0)
  38. chanBits = 0b11010000 ;
  39. else
  40. chanBits = 0b11110000 ;
  41. spiData [0] = chanBits ;
  42. spiData [1] = 0 ;
  43. wiringPiSPIDataRW (node->fd, spiData, 2) ;
  44. return ((spiData [0] << 8) | (spiData [1] >> 1)) & 0x3FF ;
  45. }
  46. /*
  47. * mcp3002Setup:
  48. * Create a new wiringPi device node for an mcp3002 on the Pi's
  49. * SPI interface.
  50. *********************************************************************************
  51. */
  52. int mcp3002Setup (const int pinBase, int spiChannel)
  53. {
  54. struct wiringPiNodeStruct *node ;
  55. if (wiringPiSPISetup (spiChannel, 1000000) < 0)
  56. return FALSE ;
  57. node = wiringPiNewNode (pinBase, 2) ;
  58. node->fd = spiChannel ;
  59. node->analogRead = myAnalogRead ;
  60. return TRUE ;
  61. }