ADC (MCP3002) + Raspberry Pi 2
Wiring the ADC
- Locate SPI pins on the Raspberry Pi - In order to properly locate pins on the ADC, you must be look at it right side up. Follow the visuals posted here while the small divet faces up. For the Serial Peripheral Device hookup you will need four SPI pins: a MOSI, a MISO, and a SCLK pin for timing and general communication between the ADC and Pi board, and a CS0 pin for receiving the data. Follow the diagram to connect correctly to the board. DIN connects to pin 19: MOSI, DOUT connects to pin 21: MISO, CLK connects to pin 23: SCLK, and CS connects to pin 24: the SPIO CS0 pin.
- Hook up to power - You may hook up the voltage to a 3.3V pin as long as your data sheet does not say otherwise. Always hook up the ground wire to a GND pin for general power.
- Wire up analog input - To read analog data through the ADC you have to connect CH0 to your analog source. Because we only used CH0, we connected CH1 to the ground so as not to confuse data. For the analog photocell input, we built a voltage divider to pull up the analog signal when the photocell receives light. We matched the resistance of the voltage divider with the theoretical minimum voltage of the photocell.
Make sure that whatever analog device you are using is hooked up to the right pin of the ADC and that it has resistors to prevent damaged circuitry.
Programming the ADC
Install spidev using the follow terminal commands:
sudo apt-get install python-dev python-pip
sudo pip install python
sudo mod probe spi_bcm2708
sudo pip install spidev
echo spi_bcm2708 | sudo tee -a /etc/modules
Use read() method to read data from the ADC into python
def read(adc_channel=0, spi_channel=0): spi = spidev.SpiDev() spi.open(0, spi_channel) spi.max_speed_hz = 1200000 # 1.2 MHz cmd = 128 if adc_channel: cmd += 32 reply_bytes = spi.xfer2([cmd, 0]) reply_bitstring = ''.join(bitstring(n) for n in reply_bytes) reply = reply_bitstring[5:15] spi.close() return int(reply, 2) / 2**10