import datetime import RPi.GPIO as GPIO GPIO.setwarnings(False) 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 def mcp3204_data(): wcd = [] # ADC CH number (0-3) ch = 0 CH_MAX = 1 # sensor value MAX_VALUE = 3520 MIN_VALUE = 2420 # 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 # print(datetime.datetime.now()) while ch <= CH_MAX: inputVal0 = readadc(ch, SPICLK, SPIMOSI, SPIMISO, SPICS) dt = 100 - (inputVal0 - MIN_VALUE) / ((MAX_VALUE - MIN_VALUE) / 100) wcd.append('{:3.1f}'.format(dt)) # print(wcd[ch]) print('Channel-{0} Water Content: {1} %'.format(ch, wcd[ch])) ch += 1 return wcd if __name__ == '__main__': mcp3204_data()