From 2bb6dc18897c52f3cc7c373f53a2596dfc4ff4d0 Mon Sep 17 00:00:00 2001 From: shinncchen Date: Tue, 14 Jan 2014 10:38:12 -0600 Subject: [PATCH] Update mcp3008.py 1) It allows readadc() to be imported and used as a function without the print log on other python file 2) The GPIO is cleanup if there is a KeyboardInterrupt --- Adafruit_MCP3008/mcp3008.py | 56 +++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/Adafruit_MCP3008/mcp3008.py b/Adafruit_MCP3008/mcp3008.py index a1678a7b..73dcd7dd 100644 --- a/Adafruit_MCP3008/mcp3008.py +++ b/Adafruit_MCP3008/mcp3008.py @@ -68,27 +68,35 @@ def readadc(adcnum, clockpin, mosipin, misopin, cspin): adcout /= 2 # first bit is 'null' so drop it return adcout -# change these as desired -SPICLK = 18 -SPIMOSI = 17 -SPIMISO = 21 -SPICS = 22 - -# 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) - -# Note that bitbanging SPI is incredibly slow on the Pi as its not -# a RTOS - reading the ADC takes about 30 ms (~30 samples per second) -# which is awful for a microcontroller but better-than-nothing for Linux - -print "| #0 \t #1 \t #2 \t #3 \t #4 \t #5 \t #6 \t #7\t|" -print "-----------------------------------------------------------------" -while True: - print "|", - for adcnum in range(8): - ret = readadc(adcnum, SPICLK, SPIMOSI, SPIMISO, SPICS) - print ret,"\t", - print "|" +if __name__=='__main__': + + try: + # change these as desired + SPICLK = 18 + SPIMISO = 21 + SPIMOSI = 17 + SPICS = 22 + + # set up the SPI interface pins + GPIO.setup(SPICLK, GPIO.OUT) + GPIO.setup(SPIMISO, GPIO.IN) + GPIO.setup(SPIMOSI, GPIO.OUT) + GPIO.setup(SPICS, GPIO.OUT) + + # Note that bitbanging SPI is incredibly slow on the Pi as its not + # a RTOS - reading the ADC takes about 30 ms (~30 samples per second) + # which is awful for a microcontroller but better-than-nothing for Linux + + print "| #0 \t #1 \t #2 \t #3 \t #4 \t #5 \t #6 \t #7\t|" + print "-----------------------------------------------------------------" + while True: + print "|", + for adcnum in range(8): + ret = readadc(adcnum, SPICLK, SPIMOSI, SPIMISO, SPICS) + print ret,"\t", + print "|" + + except KeyboardInterrupt: + pass + + GPIO.cleanup()