Interfacing Raspberry Pi and Microchip MCP3304 SPI ADC

Alright. So a lot of people on blogs and forums have been busy interfacing the MCP 3008 DAC to the Raspberry Pi.

But when I came to need one, RS Components, where i do most almost all of my shopping for components, couldn’t supply one, I had to buy another one.

Still cheap, the MCP3304, but with some minor differences. It can be configured to take both single ended and balanced input, and it has 13 bits (12 unsigned), rather than the 10 positive signed bits the MCP3008 offers.

I used Python as language and adjusted some code i found on this blog: http://jeremyblythe.blogspot.dk/2012/09/raspberry-pi-hardware-spi-analog-inputs.html

The Python code:
SPI_MCP3308.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
# mcp3008_lm35.py - read an LM35 on CH0 of an MCP3008 on a Raspberry Pi
# mostly nicked from
#  http://jeremyblythe.blogspot.ca/2012/09/raspberry-pi-hardware- spi-analog-inp$
# Changed to work w. MCP3308 by Kim H. Rasmussen, June 2013
import spidev
import time

spi = spidev.SpiDev()
spi.open(0, 0)

def readadc(adcnum):

 # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
 if adcnum > 7 or adcnum < 0:
    return -1

 # Frame format: 0000 1SCC | C000 000 | 000 000
 r = spi.xfer2([((adcnum & 6) >> 1)+12 , (adcnum & 1) << 7, 0])
 adcout = ((r[1] & 15) << 8) + r[2]
 return adcout

while True:

   # Read from ADC channels and convert the bits read into the voltage
   ch1 = (readadc(1) * 3.3) / 4095
   ch2 = (readadc(2) * 3.3) / 4095
   # Divisor changed from 1023 to 4095, due to 4 more bits
   # Print the stuff just read
   print ('Voltages: ', ch1, ' ', ch2)

   time.sleep(1)

Prerequisites:

Install Python development package:

sudo apt-get update && sudo apt-get install python-dev

Enable SPI to be loaded into the kernel on boot:

sudo raspi-config

And enable SPI on boot in The advanced menu <8>.

Install spi-dev via a terminal:

git clone git://github.com/doceme/py-spidev

cd py-spidev/

sudo python setup.py install