#!/usr/bin/python # # analogmux.py # # Mar.21/2015: v1.00 released # # MCP3208 and 74HC138N data acquisition library with SPI multiplexer # for the Raspberry Pi. Please see URL below for the introductory article. # # http://www.mikronauts.com/raspberry-pi/raspberry-pi-analog-to-digital-conversion-experiments-and-howto # # Copyright 2015 William Henning # http://Mikronauts.com # # supports up to eight MCP3208 12 bit analog to digital converters for up to 64 analog inputs # # tested with three MCP3208's # # should also work with MCP3008 with a modified readadc() # import RPi.GPIO as GPIO import spidev import time # module constants for the GPIO channels A2 = 25 A1 = 24 A0 = 23 # make a list of requests to spead up readadc req=[[6,0,0], [6,64,0],[6,128,0],[6,192,0],[7,0,0], [7,64,0],[7,128,0],[7,192,0]] # list is based on 'r = spi.xfer2([6|(adcnum>>2),(adcnum&3)<<6,0])' which in turn was based on readadc12 from # http://git.agocontrol.com/apagg/agocontrol-work/blob/93f7d9051aebf79c794e3d5fa4feea92c9221831/raspiMCP3xxxGPIO/MCP3208.py # choose the current SPI device (one of eight) def spi_device(devno): GPIO.output(A2,(devno >> 2)&1) GPIO.output(A1,(devno >> 1)&1) GPIO.output(A0,devno & 1) # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7) def readadc(adcnum): r = spi.xfer2(req[adcnum]) return ((r[1]&15)<<8) + r[2] # set up the demultiplexer GPIO.setmode(GPIO.BCM) GPIO.setup(A2, GPIO.OUT) GPIO.setup(A1, GPIO.OUT) GPIO.setup(A0, GPIO.OUT) spi = spidev.SpiDev() spi.open(0,1) # port=0, CS=1 spi.max_speed_hz=1953000 # any faster and we lose ADC resolution count = 1 while 1: print "--------------------------" print "SPI DEVICE", n, "SCAN ", count spi_device(1) mul=0.002 csv = time.asctime() # start each csv line with a time stamp for chan in range(0,8): x = readadc(chan) csv = csv + "," + str(x*mul) print chan, x*mul csv = csv + "\n" f = open("csv.txt","a") f.write(csv) f.close() time.sleep(15) count = count + 1