import os.path import time import datetime import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) filename = '/home/pi/data.txt' if not os.path.exists(filename): with open(filename, mode = 'w') as f: f.write('' + '\n\n') # 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) ch = 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: print("Time: " + str(datetime.datetime.now())) with open(filename, mode = 'a') as f: f.write("Time: " + str(datetime.datetime.now())) while ch < 4: inputVal0 = readadc(ch, SPICLK, SPIMOSI, SPIMISO, SPICS) print(str(ch) + ': ', inputVal0) with open(filename, mode = 'a') as f: f.write('\n' + str(ch) + ': ' + str(inputVal0)) ch += 1 time.sleep(1) except KeyboardInterrupt: pass with open(filename, mode = 'a') as f: f.write('\n\n') GPIO.cleanup()