Skip to content

Instantly share code, notes, and snippets.

@vallettea
Last active November 29, 2015 07:43
Show Gist options
  • Save vallettea/1b10a540dce67501f052 to your computer and use it in GitHub Desktop.
Save vallettea/1b10a540dce67501f052 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import RPi.GPIO as GPIO, time, os
GPIO.setmode(GPIO.BCM)
class PINS:
SPICLK = 11
SPIMISO = 9
SPIMOSI = 10
SPICS = 8
# set up the SPI interface pins
def initialize():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(PINS.SPIMOSI, GPIO.OUT)
GPIO.setup(PINS.SPIMISO, GPIO.IN)
GPIO.setup(PINS.SPICLK, GPIO.OUT)
GPIO.setup(PINS.SPICS, GPIO.OUT)
def readMCP3008(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)
GPIO.output(clockpin, False) # start clock low
GPIO.output(cspin, False) # bring CS low
commandout = adcnum # 101 for adcnum of 5
# 0x18 # 0001 1000 we can read hexa by grouping by four
commandout |= 0x18 # 0001 1101 now the two bits for start and mod are set
commandout <<= 3 # 1110 1000 we only need to send 5 bits here
for i in range(5):
# 1110 1000 commandout
# 1000 0000 0x80 with & gives
# true if the bit we want to transit is 1 false if not
if (commandout & 0x80):
GPIO.output(mosipin, True)
else:
GPIO.output(mosipin, False)
commandout <<= 1
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout = 0
# read in one empty bit, one null bit and 10 ADC bits
for i in range(12):
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout <<= 1
if (GPIO.input(misopin)):
adcout |= 0x1
GPIO.output(cspin, True)
adcout /= 2 # first bit is 'null' so drop it
return adcout
def readMCP3002(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 1) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)
GPIO.output(clockpin, False) # start clock low
GPIO.output(cspin, False) # bring CS low
commandout = adcnum # 1 for 1
commandout <<= 1 # 10
# 0x0D # 0000 1101
commandout |= 0x0D # 0000 1111 start bit + single-ended bit + MSBF bit
commandout <<= 4 # 1111 0000 we only need to send 4 bits here
for i in range(4):
if (commandout & 0x80):
GPIO.output(mosipin, True)
else:
GPIO.output(mosipin, False)
commandout <<= 1
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout = 0
# read in one null bit and 10 ADC bits
for i in range(11):
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout <<= 1
if (GPIO.input(misopin)):
adcout |= 0x1
GPIO.output(cspin, True)
adcout /= 2 # first bit is 'null' so drop it
return adcout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment