import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # read SPI data from MCP3204 chip, 4 possible adc's (0 thru 3) def readadc(adcnum, clockpin, mosipin, misopin, cspin): if adcnum > 3 or adcnum < 0: return -1 GPIO.output(cspin, GPIO.HIGH) GPIO.output(clockpin, GPIO.LOW) GPIO.output(cspin, GPIO.LOW) commandout = adcnum commandout |= 0x18 # start bit + single-ended bit commandout <<= 3 # we only need to send 5 bits here for i in range(5): if commandout & 0x80: GPIO.output(mosipin, GPIO.HIGH) else: GPIO.output(mosipin, GPIO.LOW) commandout <<= 1 GPIO.output(clockpin, GPIO.HIGH) GPIO.output(clockpin, GPIO.LOW) adcout = 0 # read in one empty bit, one null bit and 10 ADC bits for i in range(13): GPIO.output(clockpin, GPIO.HIGH) GPIO.output(clockpin, GPIO.LOW) adcout <<= 1 if 0 < i and GPIO.input(misopin) == GPIO.HIGH: adcout |= 0x1 GPIO.output(cspin, GPIO.HIGH) return adcout # ADC CH number (0-3) ADCCH = 0 # SPI port on the ADC to the Cobbler SPICLK = 18 SPIMISO = 23 SPIMOSI = 24 SPICS = 25 # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) # to indicate ADC data try: while True: inputVal0 = readadc(ADCCH, SPICLK, SPIMOSI, SPIMISO, SPICS) print(inputVal0) time.sleep(0.5) except KeyboardInterrupt: print("Cleanup") GPIO.cleanup()