Guest User

Raspberry Pi SPI input from MCP3008 IC

a guest
Mar 24th, 2013
1,176
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!sudo /usr/bin/python
  2.  
  3. import signal
  4. import sys
  5. import spidev
  6. import time
  7.  
  8.  
  9. def signal_handler(signal, frame):
  10.     print 'Cleaning up...'
  11.     sys.exit(0)
  12.  
  13.  
  14. # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
  15. def readadc(adcnum):
  16.     if ((adcnum > 7) or (adcnum < 0)):
  17.             return -1
  18.     r = spi.xfer2([1, (8 + adcnum) << 4, 0])
  19.     adcout = ((r[1] & 3) << 8) + r[2]
  20.     return adcout
  21.  
  22.  
  23. signal.signal(signal.SIGINT, signal_handler)
  24.  
  25. DEBUG = 1
  26.  
  27. spi = spidev.SpiDev()
  28. spi.open(0, 0)
  29.  
  30. print "Max Speed: %d" % spi.max_speed_hz
  31. print "Bit per word: %d" % spi.bits_per_word
  32.  
  33. # Microphone analog output connected to channel 4 of mcp3008
  34. adcnum = 4
  35. sleep_time = 0.05
  36.  
  37. while True:
  38.     read_adc0 = readadc(adcnum)
  39.     psense = read_adc0 * (3.3 / 1024.0)
  40.  
  41.     if DEBUG:
  42.         #print "%.2f" % (read_adc0)
  43.         print "psense: %.2f" % psense
  44.  
  45.     time.sleep(sleep_time)
RAW Paste Data