Guest User

Untitled

a guest
Feb 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import time
  3. import os
  4. import RPi.GPIO as GPIO
  5.  
  6. # GPIO
  7. GPIO.setmode(GPIO.BCM)
  8. DEBUG = 1
  9.  
  10.  
  11. # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
  12. def readadc(adcnum, clockpin, mosipin, misopin, cspin):
  13. if ((adcnum > 7) or (adcnum < 0)):
  14. return -1
  15. GPIO.output(cspin, True)
  16.  
  17. GPIO.output(clockpin, False) # start clock low
  18. GPIO.output(cspin, False) # bring CS low
  19.  
  20. commandout = adcnum
  21. commandout |= 0x18 # start bit + single-ended bit
  22. commandout <<= 3 # we only need to send 5 bits here
  23. for i in range(5):
  24. if (commandout & 0x80):
  25. GPIO.output(mosipin, True)
  26. else:
  27. GPIO.output(mosipin, False)
  28. commandout <<= 1
  29. GPIO.output(clockpin, True)
  30. GPIO.output(clockpin, False)
  31.  
  32. adcout = 0
  33. # read in one empty bit, one null bit and 10 ADC bits
  34. for i in range(12):
  35. GPIO.output(clockpin, True)
  36. GPIO.output(clockpin, False)
  37. adcout <<= 1
  38. if (GPIO.input(misopin)):
  39. adcout |= 0x1
  40.  
  41. GPIO.output(cspin, True)
  42.  
  43. adcout >>= 1 # first bit is 'null' so drop it
  44. return adcout
  45.  
  46. # change these as desired - they're the pins connected from the
  47. # SPI port on the ADC to the RPi
  48. SPICLK = 18
  49. SPIMISO = 23
  50. SPIMOSI = 24
  51. SPICS = 25
  52.  
  53. # set up the SPI interface pins
  54. GPIO.setup(SPIMOSI, GPIO.OUT)
  55. GPIO.setup(SPIMISO, GPIO.IN)
  56. GPIO.setup(SPICLK, GPIO.OUT)
  57. GPIO.setup(SPICS, GPIO.OUT)
  58.  
  59. # ultrasonic sensor connected to adc #0
  60. ultrasonic_adc_0 = 0;
  61.  
  62. try:
  63. while True:
  64.  
  65. distance_0 = readadc(ultrasonic_adc_0, SPICLK, SPIMOSI, SPIMISO, SPICS)
  66. print "distance 0:", distance_0
  67.  
  68. # hang out and do nothing
  69. # depending on the sensor the reading cycle might happen every 50ms or 100ms
  70. time.sleep(0.05)
  71.  
  72. except KeyboardInterrupt:
  73. GPIO.cleanup()
  74.  
  75. import time
  76.  
  77. # Import SPI library (for hardware SPI) and MCP3008 library.
  78. import Adafruit_GPIO.SPI as SPI
  79. import Adafruit_MCP3008
  80. # Software SPI configuration:
  81. CLK = 18
  82. MISO = 23
  83. MOSI = 24
  84. CS = 25
  85. mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
  86. while True:
  87. values[0] = mcp.read_adc(0)
  88. print "the distance is : ", values, 'cm"
  89. time.sleep(0.5)
Add Comment
Please, Sign In to add comment